首页 > 其他 > 详细

(DP)Best Time to Buy and Sell Stock

时间:2015-05-15 19:25:07      阅读:124      评论: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天价格为prices[i],假设只能进行一次买进,一次卖出,请找出最大利润值。


解:

以prices[i]表示第i天股票价格,profit[i]表示到第i天为止所能获取的最大利润。

考虑在第n天卖出股票的最大利润 profit[n]=max(profit[n-1],  prices[n]-min), 其中min为前n-1天的股票最低价。

可见我们必须在遍历数组的过程中记录最小值。

而且profit只跟前一个状态有关,所以只需用一个值来记录,而不用数组。

 


 

Java代码:

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0)
            return 0;
        int min = prices[0];
        int profit = 0;
        for(int i = 1; i < prices.length; i++){
            min = prices[i] < min ? prices[i] : min;
            profit = prices[i] - min > profit ? prices[i] - min : profit;
        }
        return profit;
    }
}

 

Python代码:

class Solution:
    # @param {integer[]} prices
    # @return {integer}
    def maxProfit(self, prices):
        if not prices:
            return 0
        tmin = prices[0]
        profit = 0
        for each in prices[1:]:
            profit = max(profit, each-tmin)
            tmin = min(each, tmin)
        return profit

 

(DP)Best Time to Buy and Sell Stock

原文:http://www.cnblogs.com/axolotl/p/4484676.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!