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

LeetCode: Best Time to Buy and Sell Stock [121]

时间:2014-06-08 15:11:58      阅读:298      评论:0      收藏:0      [点我收藏+]

标签: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.



【题意】

    给定一个数组prices, prices[i]表示第i天的股价。只允许做一次股票交易(只能一次买入,一次卖出),要求计算最大获利是多少?


【思路】

    只需要维护一个指针p,一遍扫描数组即可。 在扫描的过程中记录当前位置p之前的最小值,每到以为位置p, 就可以计算在当前位置卖出是的最大收益。与全局最大收益比较后更新即可。


【代码】

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int size=prices.size();
        if(size<=1)return 0;
        
        int maxProfit=0;
        int minPrice=INT_MAX;
        for(int i=0; i<size; i++){
            if(minPrice!=INT_MAX){
                //计算第i天卖出的最大收益
                if(prices[i]-minPrice > maxProfit) maxProfit=prices[i]-minPrice;
            }
            //更新最小股价
            if(prices[i]<minPrice)minPrice=prices[i];
        }
        return maxProfit;
    }
};


LeetCode: Best Time to Buy and Sell Stock [121],布布扣,bubuko.com

LeetCode: Best Time to Buy and Sell Stock [121]

标签:leetcode   算法   面试   

原文地址:http://blog.csdn.net/harryhuang1990/article/details/28850365

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