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 (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
可以随便买卖,求最大利益,这个其实就是把所有上涨的区间加起来:
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
var low;
var high;
var profit=0;
for (var i = 1;i < prices.length;i++) {
if (prices[i-1]<=prices[i]) {
if (low===undefined)
low = prices[i-1];
high = prices[i];
}
if (prices[i-1]>prices[i]) {
if (low!==undefined&&high!==undefined) {
profit+=(high-low);
low=undefined;
hight=undefined;
}
}
}
if (low!==undefined&&high!==undefined)
profit+=(high-low);
return profit;
};
再仔细想想的话,其实只要有上涨就加就好了:
var maxProfit = function(prices) {
var profit = 0;
for (var i=0; i< prices.length-1; i++) {
if (prices[i+1]>prices[i]) profit += prices[i+1]-prices[i];
}
return profit;
};