Skip to content

Commit 5bddbad

Browse files
committed
122.py
1 parent 601185c commit 5bddbad

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

101-200/122.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'''
2+
Say you have an array prices 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 (i.e., buy one and sell one share of the stock multiple times).
5+
6+
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
7+
8+
Example 1:
9+
10+
Input: [7,1,5,3,6,4]
11+
Output: 7
12+
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
13+
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
14+
Example 2:
15+
16+
Input: [1,2,3,4,5]
17+
Output: 4
18+
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
19+
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
20+
engaging multiple transactions at the same time. You must sell before buying again.
21+
Example 3:
22+
23+
Input: [7,6,4,3,1]
24+
Output: 0
25+
Explanation: In this case, no transaction is done, i.e. max profit = 0.
26+
'''
27+
class Solution:
28+
def maxProfit(self, prices: List[int]) -> int:
29+
30+
res = 0
31+
for i in range(1, len(prices)):
32+
profit = prices[i] - prices[i-1]
33+
res += max(profit, 0)
34+
return res
35+
36+

0 commit comments

Comments
 (0)