Leet code 121, what I wrote runs well in spyder / jupyter note . However it reports error in leetcode console

Question:

Present code here, The runtime error is resolved by initialize "maxP=0", just wondering why "maxP" here cannot be "data_in[s_point_ind]-data_in[b_point_ind]". It runs perfectly in spyder.

class Solution(object):

    def maxProfit(self, data_in:list[int]) -> int:
        
        b_point_ind = 0
        s_point_ind = 1 
        
        maxP = data_in[s_point_ind]-data_in[b_point_ind]
        
            
        while s_point_ind <= (len(data_in)-1):
            
            #profitable? 
            
            if data_in[b_point_ind] <= data_in[s_point_ind]:

                maxP = max (maxP, (data_in[s_point_ind]-data_in[b_point_ind]))
                
                s_point_ind +=1 
            # Non-profitable 
            else: 
                
                b_point_ind =s_point_ind
                s_point_ind +=1 
            
        maxP = max(0,maxP)
        return maxP
            
                            
        
        

prices = [7,1,5,3,6,4]

stock_buy = Solution()

profit  = stock_buy.maxProfit(prices)
            

Attached Error message that leetcode web provided.
enter image description here
Attached Leetcode question here
enter image description here

Only Thing I change is maxP =0, then leet code accepts.

class Solution(object):

    def maxProfit(self, data_in:list[int]) -> int:
        
        b_point_ind = 0
        s_point_ind = 1 
        
       ** maxP = 0**
        
            
        while s_point_ind <= (len(data_in)-1):
            
            #profitable? 
            
            if data_in[b_point_ind] <= data_in[s_point_ind]:

                maxP = max (maxP, (data_in[s_point_ind]-data_in[b_point_ind]))
                
                s_point_ind +=1 
            # Non-profitable 
            else: 
                
                b_point_ind =s_point_ind
                s_point_ind +=1 
            
        maxP = max(0,maxP)
        return maxP
            
                            
        
        

prices = [7,1,5,3,6,4]

stock_buy = Solution()

profit  = stock_buy.maxProfit(prices)
Asked By: Dummy1

||

Answers:

If the data_in list contains fewer than 2 elements then data_in[1] will raise IndexError

Also, you may find this more efficient:

def maxProfit(self, prices):
        _max = 0
        if prices:
            _min = prices[0]
            for price in prices[1:]:
                if price < _min:
                    _min = price
                elif price - _min > _max:
                    _max = price - _min
        return _max
Answered By: Fred
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.