题解 | 买卖股票的最好时机(二)

买卖股票的最好时机(二)

https://www.nowcoder.com/practice/9e5e3c2603064829b0a0bbfca10594e9

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 计算最大收益
     * @param prices int整型一维数组 股票每一天的价格
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        // return solution1(prices);
        //return solution2(prices);
        return solution3(prices);
    }

    public int solution3 (int[] prices) {
        int result = 0;
        for (int i = 1; i < prices.length ; i ++) {
            // 只要某段在递增 就是有收益
            if (prices[i - 1] < prices[i]) {
                result += prices[i] - prices[i - 1];
            }
        }
        return result;
    }

    public int solution2 (int[] prices) {
        if (prices == null || prices.length < 2)
            return 0;
        int length = prices.length;
        //初始条件
        int hold = -prices[0];//持有股票
        int noHold = 0;//没持有股票
        for (int i = 1; i < length; i++) {
            //递推公式转化的
            noHold = Math.max(noHold, hold + prices[i]);
            hold = Math.max(hold, noHold - prices[i]);
        }
        //最后一天肯定是手里没有股票的时候利润才会最大,
        //所以这里返回的是noHold
        return noHold;
    }

    public int solution1 (int[] prices) {
        int length = prices.length;
        // dp[i][0] 表示第i天不持股,到该天为止的最大收益
        // dp[i][1] 表示第i天持股  ,到该天为止的最大收益
        int[][] dp = new int[length][2];

        // 第一天不持股,总收益为0
        dp[0][0] = 0;
        // 第一天持股,总收益为买股票的话费,此时为负数
        dp[0][1] = -prices[0];

        // 遍历后续每天,状态转移
        for (int i = 1; i < length; i ++) {
            //如果当天不持股,
            // 有可能是前面若干条中卖掉了或者还没有买,因此到此为止的总收益和前一天一样
            // 也有可能是当天卖掉股票
            // 收益我们选择较大的状态
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            // 如果当天持股,
            // 可能是前几天买入的还没有卖,因此和前一天相同
            // 也有可能是当天卖出,减去买入的花费
            // 收益我们选择较大的状态
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
        }
        // 最后一天不持股,到该天为止的最大收益
        return dp[length - 1][0];
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务