原题链接:
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii
解法1:
动态规划
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
|
class Solution { public int maxProfit(int[] prices) { int n = prices.length; int [][] f = new int[n + 1][5]; f[0][0] = 0; f[0][1] = -prices[0]; f[0][2] = 0; f[0][3] = -prices[0]; f[0][4] = 0;
for(int i = 1; i < n ; i++){ f[i][0] = f[i - 1][0]; f[i][1] = Math.max(f[i - 1][1],f[i - 1][0] - prices[i]); f[i][2] = Math.max(f[i - 1][2],f[i - 1][1] + prices[i]); f[i][3] = Math.max(f[i - 1][3],f[i - 1][2] - prices[i]); f[i][4] = Math.max(f[i - 1][4],f[i - 1][3] + prices[i]); }
return Math.max(f[n - 1][2],f[n - 1][4]); } }
|