标签:
题目:
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.
分析:一维的动态规划(硬算就行吧)
设dp[i]是[0,1,2...i]区间的最大利润,则该问题的一维动态规划方程如下
dp[i+1] = max{dp[i], prices[i+1] - minprices} ,minprices是区间[0,1,2...,i]内的最低价格
我们要求解的最大利润 = max{dp[0], dp[1], dp[2], ..., dp[n-1]}
其实关键就是一个是维护最大的利润的记录,一个是维护最大,最小值的记录。且最大值和最小值的其中一个需要和最大利润联动
代码:
public int maxProfit(int[] prices) { if(prices == null || prices.length == 0){ return 0; } int Profit = 0; int Min = prices[0]; int Max = prices[0]; for(int i =1 ;i<prices.length;i++ ){ if(prices[i] - Min > Profit){ Max = prices[i]; Profit = Max - Min; }else if(prices[i] - Min < Profit && prices[i] < Min){ Min = prices[i]; } } return Profit; }
[LeetCode]: 121: Best Time to Buy and Sell Stock
标签:
原文地址:http://www.cnblogs.com/savageclc26/p/4871251.html