Skip to content

Commit 99d43ac

Browse files
committed
O(n) time and O(1) using Greedy Approach.
1 parent 7405f91 commit 99d43ac

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"""
2+
Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.
3+
4+
You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)
5+
6+
Return the maximum profit you can make.
7+
8+
Example 1:
9+
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
10+
Output: 8
11+
Explanation: The maximum profit can be achieved by:
12+
Buying at prices[0] = 1
13+
Selling at prices[3] = 8
14+
Buying at prices[4] = 4
15+
Selling at prices[5] = 9
16+
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
17+
Note:
18+
19+
0 < prices.length <= 50000.
20+
0 < prices[i] < 50000.
21+
0 <= fee < 50000.
22+
"""
23+
class Solution:
24+
def maxProfit(self, prices: List[int], fee: int) -> int:
25+
min_stock = prices[0]
26+
max_profit = 0
27+
for i in range(1,len(prices)):
28+
if prices[i] < min_stock:
29+
min_stock = prices[i]
30+
elif prices[i] > min_stock + fee:
31+
max_profit += prices[i] - min_stock - fee
32+
min_stock = prices[i] - fee
33+
return max_profit

0 commit comments

Comments
 (0)