码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]31. Best Time to Buy and Sell Stock股票买卖

时间:2015-10-17 21:55:09      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
};

 

[LeetCode]31. Best Time to Buy and Sell Stock股票买卖

标签:

原文地址:http://www.cnblogs.com/aprilcheny/p/4888184.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!