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).
这道题理解了题意就会发现题目很简单。题意是说可以多次买卖,但任何时候只能手持一只股票。也就是就是说我可以买了然后卖,接着继续买了又卖,这样子。如果想清楚了,问题就会抽象成在这个数组里面累加后前两个元素的差值,当后面元素大于前面元素,也就可以从前面元素买入后面元素卖出,赚取差额;当后面元素小于前面元素就什么都不做就好了。
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0){
return 0;
}
int max = 0;
for (int i = 0; i < prices.length - 1; i++){
if (prices[i + 1] > prices[i]){
max += prices[i + 1] - prices[i];
}
}
return max;
}
}