题目
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
No.121是能买卖一次 No.122是可以多次买卖达到利益最大化
思路
No.121
- 遍历交易天数,寻找最低点,记录后续交易日与最低点的差值,记录最大的差值;
- 后续交易日有更低的日期,则重置最低点,重复步骤1;
No.122
- 遍历交易天数,记录昨天的交易额,如果今日的交易额大于昨日的,则收益增加
// No.122
var maxProfit = function(prices) {
var lastPrice = Infinity;
var res = 0;
for (let i = 0; i < prices.length; i++) {
if (prices[i] > lastPrice) {
res += prices[i] - lastPrice
}
lastPrice = prices[i];
}
return res;
}