-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuy_and_sell_stock.py
51 lines (37 loc) · 1.33 KB
/
buy_and_sell_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
44
45
46
47
48
49
50
51
#https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
def maxProfit(self, prices: List[int]) -> int:
min_price = float('inf')
max_prof = 0
for price in prices:
if price < min_price:
min_price = price
max_prof = max(max_prof, (price-min_price))
return max_prof
#some thing new I learned from this question:
#1. float('inf') infinity used to initialize and update to find the minimum number
#2. in this question, loop over the array once, while looping, keep holding of the min
# price, and update the max_profit using max built-in method.
# Two point
class Solution:
def maxProfit(self, prices: List[int]) -> int:
#update left pointer to the newest low
#then proceed the right pointer to one direction
left = 0
right =1
max_p = 0
while right < len(prices):
if prices[right] < prices[left]:
left = right
right +=1
else:
max_p = max(max_p, prices[right]- prices[left])
right+=1
return max_p
def findMaxProfit(arr):
maxProfit = 0
minPrice = arr[0]
for i in range(1, len(arr)):
currProfit = arr[i] - minPrice
maxProfit = max(maxProfit, currProfit)
minPrice = min(minPrice, arr[i])
return maxProfit