Skip to content

Commit 76d9806

Browse files
123. Best Time to Buy and Sell Stock III (java)
1 parent 986cf0b commit 76d9806

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
public int maxProfit(int[] prices) {
3+
if (prices.length <= 1) return 0;
4+
int m = 2 , n = prices.length;
5+
int[][] dp = new int[m+1][n];
6+
for (int i = 1; i <= m; i++) {
7+
int maxdiff = Integer.MIN_VALUE;
8+
for (int j = 1; j < n; j++) {
9+
maxdiff = Math.max(maxdiff, dp[i-1][j-1] - prices[j-1]);
10+
dp[i][j] = Math.max(dp[i][j-1], prices[j] + maxdiff);
11+
}
12+
}
13+
return dp[m][n-1];
14+
}
15+
}

0 commit comments

Comments
 (0)