Home > Back-end >  How to solve Time exceeded problem in Best Time to buy stock simple leetcode question
How to solve Time exceeded problem in Best Time to buy stock simple leetcode question

Time:01-24

I am solving the leetcode question of Best Time to buy stock: I have submitted this code with one for loop and I have got time limit exceeded. I cannot figure out why.

class Solution(object):
def maxProfit(self, prices):
    maxPro = 0
    size = len(prices)
    for i in range(size-1,0,-1):
        minimum = min(prices[0:i])
        maxPro = max(prices[i]-minimum,maxPro)
    return maxPro

please help

CodePudding user response:

From TimeComplexity min() and max() functions have O(n) complexity on List, so it is basically another loop. So your time complexity is O(n^2)

  •  Tags:  
  • Related