121. Best Time to Buy and Sell Stock

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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

解题思路:

给定一个股票的价格序列prices,但是仅能交易一次,求最大利润。也就是找出max(prices[j]-prices[i]),其中j > i。要求只需要遍历一次序列就好了,那么就有两种思路。第一种,每次找到当前最小的价格low,将当前的利润与最大利润做比较,直至得到最大利润;第二种利用动态规划的思想,用d[i]来i表示如果在第i天买出得到的最大利润d[i] = max(d[i - 1] + prices[i] - prices[i - 1],0)。
现在给出第二种思路的代码:

code:

int maxProfit(vector<int>& prices)
 {
        vector<int> d(prices.size(), 0);
        int maxp = 0;
        for (int i = 1; i < prices.size(); i++) {
            d[i] = d[i - 1] + prices[i] - prices[i - 1];
            d[i] = max(0,d[i]);
            if (maxp < d[i])
              maxp = d[i];
        }
        return maxp;
 }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容