您的位置:首页 > 编程语言 > Java开发

LeetCode | Best Time to Buy and Sell Stock

2014-02-23 18:19 267 查看
题目

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.
分析
遍历一遍数组,遍历过程中,始终记录最小值,即遍历到当前节点所能看到的最佳买入价格。当被遍历节点不是最小值时,计算其与最小值的差价,从而判断是否有最大收益。

代码

public class BestTimeToBuyAndSellStock {
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1) {
return 0;
}

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