题目:
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
由于只能买卖一次股票,所以针对每天的价格要找到之前股票价格的最小值,这样才使得利润最大。即对于prices[]数组中的每个值,要找到这个值左边的最小值。下面直接上代码:
Java版本:
public int maxProfit(int[] prices) {
//没有买入股票或者在第一天买入了股票
if(prices == null || prices.length <= 1) return 0;
//每次交易都找到左边的最小值,这样每次利润才最大,然后比较选取每次利润的最大值
int max = 0 ,minPrices = prices[0];
for(int i=1;i < prices.length;i++){
minPrices = Math.min(minPrices,prices[i-1]);
if(minPrices < prices[i]){
max = Math.max(prices[i] - minPrices, max);
}
}
return max;
}
JS版本:
var maxProfit = function(prices) {
//每次交易都找到左边的最小值,这样每次利润才最大,然后比较选取每次利润的最大值
if(prices == null || prices.length <= 1) return 0;
let max = 0;
let minprices = prices[0];
for(let i = 1;i<prices.length;i++){
minprices = Math.min(minprices,prices[i]);
max = Math.max(max,prices[i] - minprices);
}
return max;
};