[LeetCode] Best Time to Buy and Sell Stock

来源:互联网 发布:win7开软件盘 编辑:程序博客网 时间:2024/05/17 02:49

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

题目解析:
这道题目也是一道动态规划的题目,所求的是利益的最大值,即求某一天买和某一天卖赚取的利润最大值。这里不能使用贪心算法直接找出最大最小值的差值,所以必须先购入后售出,因此这里必须从第一天开始对数组进行扫描,维护两个值,一个是最大利益profit,一个是最小商品价格。第一天的时候,最小商品价格就是第一天的价格,利益为0,而后递增,当当天的利益大于profit时,更新profit的值,同时比较价格,保留最小的价格,这样以O(n)的复杂度即可以找出最大的利益profit。

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