您的位置:首页 > 其它

LeetCode 121 Best Time to Buy and Sell Stock

2016-04-11 23:28 435 查看
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个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

给出一个数组样例[3,2,3,1,2], 返回 1。

此题目为dp(动态规划)问题。第i天卖出的最大收益即为第i天的股市价格减去[0,i-1]天内的最小股市价格,如果这个值大于当前最大利润值,就更新当前最大利润值。当第i天的股市价格比[0,i-1]天内最低股市价格还低,则更新最低股市价格。

public int maxProfit(int[] prices) {
if (prices.length == 0) return 0;
int minbuy = prices[0], profit = 0;
for (int i = 1; i < prices.length; i++) {
minbuy = Math.min(prices[i], minbuy);
profit = Math.max(profit, prices[i] - minbuy);
}
return profit;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: