动态规划股票

股票交易

  1. 股票交易一: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
    思路:一次遍历取, dp[i]表示第i天能获取的最大利润,minprice为第i天之前的最小股票成本,dp[i]=prices[i]-minprice, dp[]中的最大值为所求最大利润
    下面的解法进行了空间优化,很明显只需要一个变量maxprofit每一轮max即可
public class Solution {
    public int maxProfit(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice) {
                minprice = prices[i];
            } else if (prices[i] - minprice > maxprofit) {
                maxprofit = prices[i] - minprice;
            }
        }
        return maxprofit;
    }
  1. 股票交易二: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
    思路:总利润其实为所有递增的区间,
class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) {
                res += prices[i] - prices[i - 1];
            }
        }
        return res;
    }
}
  1. 股票交易三:
    思路:状态机思路,用一个二维数组,dp[i][j]中的j代表不同的状态
class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length == 0) return 0;
        int [][] dp = new int[prices.length][3];
        dp[0][1] -= prices[0];
        for (int i = 1; i < prices.length; i++) {
            //0代表不持有股票但不处于冷冻期,1代表持有股票,2代表不持有处于冷冻期
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][2]);
            dp[i][1] = Math.max(dp[i-1][0] - prices[i], dp[i-1][1]);
            dp[i][2] = dp[i-1][1] + prices[i];
        }
        return Math.max(dp[prices.length - 1][0], dp[prices.length - 1][2]);
    }
}
posted @ 2020-12-29 00:14  幽枫  阅读(32)  评论(0)    收藏  举报