[LeetCode]31. 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.

 

解法:限制最多允许交易一次。假设第i天交易后所获最大收益为maxv,则要使maxv最大,则要么maxv为前i-1天交易后所获得的最大收益,要么就是第i天股票价格(卖出价格)减去前i-1天的最低价格(买入价格)所获的收益。使用动态规划求解。时间复杂度O(n),空间复杂度O(1)。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if (n < 2) return 0;
        int curMin = prices[0], maxVal = 0;
        for (int i = 1; i < n; i++) {
            curMin = min(curMin, prices[i]);
            maxVal = max(maxVal, prices[i] - curMin);
        }
        return maxVal;
    }
};

 

posted @ 2015-10-17 20:48  AprilCheny  阅读(185)  评论(0编辑  收藏  举报