「这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战」
今夜目标
买卖股票的最佳时机
一句话总结题目:股票只能买一次,只能卖一次
假设股票价格随着时间的数组为:[7,1,5,3,6,4]
如果数组长度为1,只能买,不能卖,所以买卖收益为0;
如果数组大于1;请看下图;
假股票曾经最低价格为min,min初始值为第1天的股票价;
设经过第i天,min的最低价为 min =数组 [0...i] 最小值;
当前i天如果卖出股票收益最大是: 当天股票价格 - min(曾经股票最低价)
结果是result 、 价格 - min的最大值
| 时间 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| 价格 | 7 | 1 | 5 | 3 | 6 | 4 |
| min | 7 | 1 | 1 | 1 | 1 | 1 |
| result | 0 | 0 | 4 | 2 | 5 | 3 |
根据上述思路编辑代码如下
var maxProfit = function(prices) {
const len = prices.length;
if(len === 1) return 0;
let min = prices[0];
let result = 0;
for(let i = 1 ; i < len; i++){
if(prices[i] > min){
result = Math.max(result,prices[i] - min)
}else{
min = prices[i]
}
}
return result
};
买卖股票的最佳时机 II
哈哈,接上题;现在股票可以随时买随时卖了;
还是假设股票价格随着时间的数组为:prices = [7,1,5,3,6,4];
分析第i天和第i-1天收益;i>=1
假如:第i天股票价格高于第i-1天股票;第i天收益prices[i] - prices[i-1]
| i天 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| 价格 | 1 | 5 | 3 | 6 | 4 | |
| i-1天价格 | 7 | 1 | 5 | 3 | 6 | 4 |
| result | 0 | 4 | 0 | 3 | 0 | 0 |
result = 7
根据上述思路编辑代码如下:
var maxProfit = function(prices) {
const len = prices.length;
if(len === 1) return 0;
let result = 0;
for(let i = 1 ; i < len ; i++){
if(prices[i] > prices[i-1]){
result+= (prices[i] - prices[i-1])
}
}
return result
};
买卖股票的最佳时机 III
未完待续!!!!!