题目
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 1
Input: [7,1,5,3,6,4]
Output: 5 // 6 - 1所得
// 为什么不能7 - 1
//因为必须先买才能卖,买入价格如果是7,卖出价格就必须是7后面的数,
- Example 2
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
- 思路
利润就是卖出价格减去买入价格
在数组中,就是后面的价格减去前面的价格取得最大值
第一步: 保证买入价格是前面最小值
第二部:出现一个新价格,就
- 解法
var maxProfit = function(prices) {
let max = 0
let buy = prices[0]
for(price of prices){
// 保证买入的价格是最小的
buy = Math.min(buy,price)
// 没遇到一个新价格计算一次卖出的利润,然后对比前面卖出的利润,取最大的
max = Math.max(max, price - buy)
}
return max
};
var res = maxProfit()