-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_0122BestTimeToBuyAndSellStockii.java
64 lines (50 loc) · 1.74 KB
/
_0122BestTimeToBuyAndSellStockii.java
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
53
54
55
56
57
58
59
60
61
62
63
64
package com.heatwave.leetcode.problems;
public class _0122BestTimeToBuyAndSellStockii {
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int buy = -prices[0], sell = 0;
for (int i = 1; i < n; i++) {
buy = Math.max(buy, sell - prices[i]);
sell = Math.max(sell, buy + prices[i]);
}
return sell;
}
}
class SolutionDpOptimization {
public int maxProfit(int[] prices) {
int n = prices.length;
int buyYesterday = -prices[0], sellYesterday = 0;
int buyToday = 0, sellToday = 0;
for (int i = 1; i < n; i++) {
buyToday = Math.max(buyYesterday, sellYesterday - prices[i]);
sellToday = Math.max(sellYesterday, buyYesterday + prices[i]);
buyYesterday = buyToday;
sellYesterday = sellToday;
}
return sellToday;
}
}
class SolutionDpExceedMemoryLimit {
public int maxProfit(int[] prices) {
int n = prices.length;
int[][] dp = new int[n + 1][n + 1];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < n; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[n - 1][0];
}
}
class SolutionGreedy {
public int maxProfit(int[] prices) {
int n = prices.length, ans = 0;
for (int i = 1; i < n; i++) {
ans += Math.max(0, prices[i] - prices[i - 1]);
}
return ans;
}
}
}