赞
踩
一维数组写法:
- class Solution {
- public int maxProfit(int[] prices) {
- int n = prices.length;
- if(n == 1) return 0;
- //表示4个状态,第一次买入、卖出、第二次买入、卖出
- //买入不一定要当天买入,有可能为保持最大值维持上一次的买入
- int[] dp = new int[4];
- dp[0] = -prices[0];
- dp[1] = 0;
- dp[2] = -prices[0];
- dp[3] = 0;
- for(int i = 1; i < n; i++){
- dp[0] = Math.max(dp[0], -prices[i]);
- dp[1] = Math.max(dp[1], dp[0] + prices[i]);
- dp[2] = Math.max(dp[2], dp[1] - prices[i]);
- dp[3] = Math.max(dp[3], dp[2] + prices[i]);
- }
- return dp[3];
- }
- }
二维数组写法:
- class Solution {
- public int maxProfit(int[] prices) {
- int n = prices.length;
- if(n == 1) return 0;
- int[][] dp = new int[n][4];
- dp[0][0] = -prices[0];
- dp[0][1] = 0;
- dp[0][2] = -prices[0];
- dp[0][3] = 0;
- for(int i = 1; i < n; i++){
- dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);
- dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
- dp[i][2] = Math.max(dp[i - 1][2], dp[i - 1][1] - prices[i]);
- dp[i][3] = Math.max(dp[i - 1][3], dp[i - 1][2] + prices[i]);
- }
- return dp[n - 1][3];
- }
- }
一维数组写法省空间,但是思路很绕,不容易理解,老老实实写二维数组,用昨天的状态来推导今天。
上一题拓展,
- class Solution {
- public int maxProfit(int k, int[] prices) {
- if(k == 0) return 0;
- int n = prices.length;
- if(n == 1 || n == 0) return 0;
- int[][] dp = new int[n][2 * k];
- //初始化第一天的买入卖出状态
- for(int i = 0; i < 2 * k; i+=2){
- dp[0][i] = -prices[0];
- }
- for(int i = 1; i < n; i++){
- dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);
- dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
- for(int j = 2; j < 2*k; j+=2){
- dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1] - prices[i]);
- dp[i][j + 1] = Math.max(dp[i - 1][j + 1], dp[i - 1][j] +prices[i]);
- }
- }
- return dp[n - 1][2*k - 1];
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。