Sabrina
Sabrina

Reputation: 13

How to solve Time exceeded problem in Best Time to buy stock simple leetcode question

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

Upvotes: 0

Views: 81

Answers (1)

Tomáš Šturm
Tomáš Šturm

Reputation: 519

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)

Upvotes: 1

Related Questions