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).
題意:121的followup,不限制交易次數(shù)了值朋,問(wèn)能獲得的最大收益是多少。
思路:因?yàn)椴幌拗平灰状螖?shù)了谴轮,所以只要相鄰的兩天有利潤(rùn),我們就可以選擇交易懂盐;如果當(dāng)天的價(jià)格比前一天低瞧壮,那么就不予考慮交易庆揪。是一種貪心的方法。
public int maxProfit(int[] prices) {
int profit = 0;
if (prices == null || prices.length < 2) {
return profit;
}
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i-1]) {
profit += prices[i] - prices[i-1];
}
}
return profit;
}