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).
可以隨便買賣,求最大利益辟狈,這個其實就是把所有上漲的區(qū)間加起來:
/**
* @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;
};
再仔細(xì)想想的話声畏,其實只要有上漲就加就好了:
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;
};