-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC_Best_Time_to_Buy_and_Sell_Stock.py
52 lines (47 loc) · 1.45 KB
/
LC_Best_Time_to_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
52
"""
run through the numbers.. store the min_number and max_profit.
update the max_profit in the process.
What remains at the end is the max_profit.
"""
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
min_price = float('inf')
max_profit = 0
for index,item in enumerate(prices):
if (item < min_price):
min_price = item
if ((prices[index]-min_price) > max_profit):
max_profit = prices[index] - min_price;
return (max_profit)
"""
When a price is less than previous day price.. consider todays price as the buy price.
if todays price is greater than previous day price... then sell it today and buy it again today.
"""
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
res = 0;
buy_price = -1;
for index,item in enumerate(prices):
if (buy_price == -1):
buy_price = item
continue;
if (buy_price < item):
res += abs(item-buy_price)
buy_price = item
continue;
if (buy_price > item):
buy_price = item;
continue;
return (res)