121. Best Time to Buy and Sell Stock(第十一周)

来源:互联网 发布:手机图片恢复软件 编辑:程序博客网 时间:2024/06/07 02:22

Description

Best Time to Buy and Sell Stock - LeetCode

Say you have an array for which the i th 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: 5max. 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: 0In this case, no transaction is done, i.e. max profit = 0.

Solution

这是一个简单的O(n)算法问题,我们首先排除空的数组,让它直接等于0。

后由样例2我们知道最少的profit为0,所以我们一开始设置profit的值就应该是0。然后标记一个最少的值,我们称为min,对于非空的数组,我们一开始把min的值设置为prices[0]的值,然后进行遍历,如果遇到比min小的值就把这个值赋给min,如果不是就将这个数和min进行相减,得到的数值与profit比较,如果比profit大,那么就将这个值赋给profit

问题解决。

代码如下:

Source Code

submission

class Solution {public:    int maxProfit(vector<int>& prices) {        if (prices.empty())        {            return 0;        }        int min = prices[0];        int profit = 0;        for (int i = 1; i < prices.size(); i++)        {            if (prices[i] < min)            {                min = prices[i];            }            else            {                if (prices[i] - min > profit)                {                    profit = prices[i] - min;                }            }        }        return profit;    }};

Comment

一个比较简单的题目,能用O(n)时间复杂度解决。

原创粉丝点击