121. Best Time to Buy and Sell Stock/动态规划

题目描述

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

解析

刚开始只想到了暴力法,看了大佬的题解才知道可以用动态规划。要想求得最大收益,首先buying price需要选择谷点,selling price需要选择峰值点,满足差值最大的一组price即为所求。
在这里插入图片描述
于是代码:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int minprice=INT_MAX,maxprofit=0;
        for(int i=0;i<prices.size();i++){
            minprice=min(prices[i],minprice); //找到值最小的谷点
            maxprofit=max(prices[i]-minprice,maxprofit);
        }
        return maxprofit;
    }
};

进一步分析

有大佬分析这个解法其实是动态规划的思想:

因为在数组中求两点的差,而两点之差可以转换成求和问题。牛顿莱布尼茨公式:
在这里插入图片描述
只不过,在这里,F() 函数不是连续的,而是离散化的.
总结下:区间和可以转换成求差的问题,求差问题,也可以转换成区间和的问题。

发布了103 篇原创文章 · 获赞 9 · 访问量 4722

猜你喜欢

转载自blog.csdn.net/weixin_43590232/article/details/104306650
今日推荐