LeetCode: 121. Best Time to Buy and Sell Stock

LeetCode: 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.

Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 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

In this case, no transaction is done, i.e. max profit = 0.

题目大意: 给定一个表示每天的股价的数组,求出只有一次买卖机会下,最大收益。

解题思路

要想在第 i 天卖出股票获得最大收益,则必须在第 i 天前股价最小的那天买入股票。 因此只需要求得第 i 天前股价的最小值,在第 i 天卖出的最大收益就是第 i 天的股价减去第 i 天前股价的最小值。最后求得使得收益最大的 i 即可。

AC 代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int frontNMinPrices = INT_MAX; // 前 i 天股价的最小值
        int profit = 0;                // 前 i 天买卖收益的最大值

        for(int i = 0; i < prices.size(); ++i)
        {
            // 计算前 i 天股价的最小值
            if(frontNMinPrices > prices[i]) frontNMinPrices = prices[i];

            // 计算第 i 天卖出收益的最大值,并判断其是不是 "前 i 天买卖收益的最大值"
            if(profit < prices[i] - frontNMinPrices)  profit = prices[i] - frontNMinPrices;
        }

        return profit;
    }
};
全部评论

相关推荐

天降大厂offer:想从事前端就放前端的技术栈,然后项目描述,还有项目做了什么内容,使用了什么技术解决了什么问题优化了什么性能。然后头像可以不要,在读也可以不要,还有bg的话就不要放课程,写哪个学校什么本科,还有绩点排名(如果高的话),然后就是技术栈写好一点,接下来就是项目(有实习就写实习,没有就到项目),项目放两个好一点的,自己包装一下,然后有参加什么竞赛放两个就好了,接下来就是靠你自己了,毕竟211还是很难容易找的,不像我们学院本
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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