LeetCode122. 买卖股票的最佳时机 II(动态规划、贪心算法)

版权声明:原创作品 https://blog.csdn.net/weixin_43093501/article/details/90263045

题目:

在这里插入图片描述

贪心算法

/***
     * 贪心算法:只要第二天的价格比今天高,就第一天买,第二天卖
     * @param prices
     * @return
     */
    public int maxProfix(int[] prices) {
        if (prices == null || prices.length == 0 || prices.length == 1) {
            return 0;
        }
        int max = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            if(prices[i+1] - prices[i] > 0){
                max += prices[i + 1] - prices[i];
            }
        }
        return max;
    }

贪心算法原理

原理链接

动态规划

public class Soulution {
    public int maxProfix(int[] prices) {
        if (prices == null || prices.length == 0 || prices.length == 1) {
            return 0;
        }

        int[][] dp = new int[prices.length][2];
        dp[0][0] = 0;
        dp[0][1] = -7;
        for (int i = 1; i < prices.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[prices.length - 1][0];
    }

猜你喜欢

转载自blog.csdn.net/weixin_43093501/article/details/90263045