其他分享
首页 > 其他分享> > [LeetCode] #121 买卖股票的最佳时机

[LeetCode] #121 买卖股票的最佳时机

作者:互联网

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。

首先暴力解法,超时了

class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        for(int i = 0;i < prices.length;i++)
            for(int j = i+1;j < prices.length;j++)
                if(prices[j]-prices[i] > 0) res = Math.max(res,prices[j]-prices[i]);
        return res;
    }
}

这道题有点类似[LeetCode] #53 最大子序和,可以动态规划,也可以贪心算法

动态规划

dp0表示 0~i天 卖出的最大收益;dp1表示 0~i天 买入的最大收益

class Solution {
    public int maxProfit(int[] prices) {
        int dp0 = 0,dp1 = -prices[0];
        for(int i = 1;i < prices.length;i++) {
            dp0 = Math.max(dp0,dp1 + prices[i]);
            dp1 = Math.max(dp1,-prices[i]);
        }
        return dp0;
    }
}

贪心算法

因为股票就买卖一次,那么贪心的想法很自然就是买入最小值,卖出最大值,那么得到的差值就是最大利润

class Solution {
    public int maxProfit(int[] prices) {
        int min = prices[0],res = 0;
        for(int i = 1; i < prices.length; i++){
            min = Math.min(min,prices[i]);
            res = Math.max(res,prices[i]-min);
        }
        return res;
    }
}

知识点:

总结:

标签:dp1,dp0,int,res,121,最佳时机,prices,LeetCode,Math
来源: https://www.cnblogs.com/jpppp/p/15128405.html