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

Best Time to Buy and Sell Stock

时间:2014-11-21 18:21:20      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   ar   color   os   sp   for   

Dynamic Programming

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.

 

C++代码实现:

#include<iostream>
#include<vector>
using namespace std;

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

int main()
{
    Solution s;
    vector<int> vec={1,4,6,8,3,5,9,3,6};
    cout<<s.maxProfit(vec)<<endl;
}

 

Best Time to Buy and Sell Stock

标签:des   style   blog   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/wuchanming/p/4113447.html

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