Skip to content

Commit a1c0877

Browse files
committed
Best Time to Buy and Sell Stock II
1 parent ecd22c1 commit a1c0877

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
'''
2+
Say you have an array for which the ith element is the price of a given stock on day i.
3+
4+
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
5+
'''
6+
7+
class Solution(object):
8+
def maxProfit(self, prices):
9+
"""
10+
:type prices: List[int]
11+
:rtype: int
12+
"""
13+
if not prices:
14+
return 0
15+
low = high = prices[0]
16+
profit = 0
17+
for i in range(1, len(prices)):
18+
if prices[i] >= prices[i - 1]:
19+
high = prices[i]
20+
else:
21+
profit += high - low
22+
low = high = prices[i]
23+
profit += high - low
24+
return profit
25+
26+
27+
if __name__ == "__main__":
28+
assert Solution().maxProfit([2, 4, 6, 1, 3, 8, 3]) == 11

0 commit comments

Comments
 (0)