Best Time to Buy and Sell Stock

121 Best Time to Buy and Sell Stock

Related:Array && Dynamic Programming
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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
example:I got array[7,1,5,3,6,4];The correct output should be 5;

解法一

1
2
3
4
5
6
7
8
9
10
11
const maxProfit = function(prices){     //maxProfit在这里起到了比较下面profit大小的作用
if(prices === null || price.lenght === 0){return 0;}
var min = Number.MAX_VALUE;
var profit = 0;
var i;
for(i=0;i<prices.length;i++){
min = prices[i]<min?:prices[i]:min; //7 1 1 1 1 1
profit = (prices[i] - min)>profit?price[i]-min:profit; //0 0 5-1 3-1 6-1 4-1
}
return profit;
}

解法二

[7,1,5,3,6,4]

1
2
3
4
5
6
7
8
9
10
const maxProfit = function (prices) {
var profit = 0, diff;
var i;
for (i = 0; i < prices.length - 1; i++) {
diff = prices[i+1] - prices[i]; //1-7 5-1 3-5 6-3 4-6
if (diff > 0) { profit += diff; } //4 3
}
return profit; //4
}
// 这里我想maxProfit是已经封装了max()函数,因为const不定义maxProfit老是报错

一起回顾下max()方法

1
2
var max = Math.max(3,54,32,16);
alert(max); //54

Best Time to Buy and Sell Stock
https://www.pengsifan.com/2018/12/10/BestTimeToBuyAndSellStock/
作者
sifan.peng
发布于
2018年12月10日
许可协议