-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprofit_stock.py
43 lines (38 loc) · 1.22 KB
/
profit_stock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
# Time exceeded
# class Solution:
# def maxProfit(self, prices) -> int:
# output = 0
# for i in range(len(prices)):
# for j in range(len(prices)):
# if i != j and j > i:
# profit = prices[j] - prices[i]
# if profit > output:
# output = profit
# return output
# Time exceeded
# class Solution:
# def maxProfit(self, prices) -> int:
# output = 0
# for i in range(len(prices)):
# subset = prices[i+1:]
# if subset:
# profit = max(subset) - prices[i]
# if profit > output:
# output = profit
# return output
class Solution:
def maxProfit(self, prices) -> int:
left, right = 0, 1
maxProfit = 0
while right < len(prices):
if prices[left] < prices[right]:
profit = prices[right] - prices[left]
maxProfit = max(profit, maxProfit)
else:
left = right
right += 1
return maxProfit
prices = [7,1,5,3,6,4]
s = Solution()
print(s.maxProfit(prices))