#121.best-time-to-buy-and-sell-stock
题目链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
参考链接:https://leetcode-cn.com/problems/first-bad-version/solution/di-yi-ge-cuo-wu-de-ban-ben-by-leetcode/
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。
注意:你不能在买入股票前卖出股票。
示例1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
示例2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
- 求出每个数和其后数字的差值,然后找出最大的
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
var max = 0
for(let i = 0; i < prices.length; i++){
for(let j = i+1; j < prices.length; j++){
var value = prices[j] - prices[i];
if(value > max){
max = value
}
}
}
return max
};
- 记录当前点之前的最小值,每次跟之前的最小值比较,得到当前点的最大利润
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
if(!prices.length){
return 0
}
var minPrice = prices[0], max = 0;
for(let i = 1; i < prices.length; i++){
var price = prices[i];
if(price < minPrice){
minPrice = price;
continue;
}
let value = price - minPrice;
if(value > max){
max = value
}
}
return max
};
- 动态规划,考虑的是当前点的值与之前值的关系,构造递推公式,然后递归计算