算法训练营Day49(买卖股票)

 121. 买卖股票的最佳时机 

121. 买卖股票的最佳时机 - 力扣(LeetCode)

dp数组

        dp[an][0] :第i天持有股票最大金额,

        dp[an][1]:第i天不持有股票最大金额

递推公式:

        dp[i][0] :

                ----昨天就有,保持:dp[i-1][0]

                ----昨天不持有,今天刚买 -price[i]   + 0{0不写,昨天不持有股票,手里没钱就是9=0)

                dp[i][0] = Math.max(dp[i-1][0],-prices[i]);

        dp[i][1]:

                ---昨天不持有,保持:dp[i-1][1]

                ---昨天有股票,今天卖的, prices[i]+dp[i-1][0] {要加上昨天持有股票手里的钱,其实是欠的钱}

                dp[i][1] = Math.max(dp[i-1][1],prices[i]+dp[i-1][0]);

class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) return 0;
        int length = prices.length;
        // dp[i][0]代表第i天持有股票的最大收益
        // dp[i][1]代表第i天不持有股票的最大收益
        int[][] dp = new int[length][2];
        int result = 0;
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        for(int i = 1;i

 122.买卖股票的最佳时机II 

122. 买卖股票的最佳时机 II - 力扣(LeetCode)

和买卖股票1 的区别是:

买入的时候,手里的现金可能是非0

dp[i][0] =Math.max(dp[i-1][0],-prices[i]+dp[i-1][1]);  //不是0了,是昨天不持有股票,今天刚买入,买入的时候,手里的钱不再是0,因为之前可能买卖多次了

class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) return 0;
        int length = prices.length;
        // dp[i][0]代表第i天持有股票的最大收益
        // dp[i][1]代表第i天不持有股票的最大收益
        int[][] dp = new int[length][2];
        int result = 0;
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        for(int i = 1;i

你可能感兴趣的:(算法)