LeetCode学习篇十六——Best Time to Buy and Sell Stock

题目: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: 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.

这道题比较简单,因为只考虑买一次和卖一次,没有其他限制条件,所以直接对数组遍历,用变量min_price存储最低价格,然后动态更新max. difference。代码实现如下,时间复杂度:O(n)

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() <= 1) return 0;
        int min_price = prices[0];
        int max_diff = 0;
        for(int i = 1; i < prices.size(); i++) {
            min_price = min(min_price,prices[i]);
            max_diff = max(max_diff, prices[i]-min_price);
        }
        return max_diff;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章