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

【LeetCode】Best Time to Buy and Sell Stock

时间:2014-11-27 00:17:48      阅读:227      评论: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.


    思路:

    只能买卖一次,所以要找一个最大差值的两天,但要注意低的那一天是在前面的。所以可以维护一个最小值和一个最大差值,从前往后走,如果比最小值小则更新,如果减最小值的差值大于之前的最大差值,则更新最大差值。

    注意如果维护的是最大值和最小值,最后返回一个最大-最小的数,会是错的哦!


     代码:

     C++:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
		int n = prices.size();
		if(n <= 1) return 0;

		int min_value = prices[0];
		int ans = 0;
		for(vector<int>::iterator it = prices.begin();it != prices.end();it++)
		{
			/* 更新最小值 */
			if(*it < min_value)
			{
				min_value = *it;
			}

			/* 更新最大差值 */
			if(*it - min_value > ans)
			{
				ans = *it - min_value;
			}
		}

		return ans;
        
    }
};

     Python:

class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        if len(prices) < 2:
            return 0
        min = prices[0]
        profit = 0
        for x in prices:
            if x < min:
                min = x
            if x - min > profit:
                profit = x-min
        return profit


【LeetCode】Best Time to Buy and Sell Stock

标签:leetcode

原文地址:http://blog.csdn.net/jcjc918/article/details/40458215

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