Skip to content

Commit 6bbd720

Browse files
committed
feat: solve best time to buy and sell stock
1 parent e9cabee commit 6bbd720

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public int maxProfit(int[] prices) {
3+
/**
4+
1. understanding
5+
- price[i]: i th day's stock price
6+
- to maximize profit, choose a single day to buy, and future day to sell.
7+
- return maximum profit
8+
- [7, 1, 5, 3, 6, 4] -> [0, 0, 4, 4, 5, 5]
9+
- [7, 6, 4, 3, 1] -> [0, 0, 0, 0, 0]
10+
2. strategy
11+
- profit = (sell price) - (buy price)
12+
3. complexity
13+
- time: O(N)
14+
- space: O(1)
15+
*/
16+
int minPrice = prices[0];
17+
for (int i = 0; i <prices.length; i++) {
18+
int tmp = prices[i];
19+
if (i == 0) {
20+
prices[i] = 0;
21+
} else {
22+
prices[i] = Math.max(prices[i-1], prices[i] - minPrice);
23+
}
24+
minPrice = Math.min(minPrice, tmp);
25+
}
26+
27+
return prices[prices.length - 1];
28+
}
29+
}
30+

0 commit comments

Comments
 (0)