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

LeetCode:Best Time to Buy and Sell Stock

时间:2014-11-19 20:34:34      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:algorithm   leetcode   

题目描述:

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.


思路:遍历数组,保存已经遍历过了的元素的最小值low。则在第i天卖出股票所能得到的最大收益为prices[i]-low,求出每天最大收益的最大值即可。


代码:

int maxProfit(vector<int> &prices)
{
    int length = prices.size();
    if(length == 0)
        return 0;
    int max_profit = 0;
    int low = prices[0];
    for(int i = 1;i < length;i++)
    {
        int temp = prices[i] - low;
        if(temp > max_profit)
            max_profit = temp;
        if(prices[i] < low)
            low = prices[i];
    }
    return max_profit;
}


LeetCode:Best Time to Buy and Sell Stock

标签:algorithm   leetcode   

原文地址:http://blog.csdn.net/yao_wust/article/details/41286819

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