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).
此题和Best Time to Buy and Sell Stock不同之处在于,交易是可以多次进行的,但是要注意 you may not engage in multiple transactions at the same time,这道题时贪心选择算法,原因是它具有贪心选择性质,即局部的最优解最终形成了整体最优解,它和动态规划的区别也在于此,所有的局部的解也都是最优解,而动态规划时肯定局部有最优解,但是不是全部。从这道题来看就是当移动到数组某一值时,之前所有的交易能挣的最多数目的钱就是最优解,代码如下:
public class Solution {
public int maxProfit(int[] prices) {
int sum = 0;
if(prices.length==0) return sum;
int start = prices[0];
for(int i=1;i<prices.length;i++){
if(prices[i]<start){
start = prices[i];
}else{
sum+=prices[i]-start;
start = prices[i];
}
}
return sum;
}
}
这里面要考虑两种情况[1,2,4],[1,5,4]第一种情况是当考虑到数组值为2的时候,之前最大是2-1的钱,当考虑到4的时候,是4-1的钱,但是算法里面体现的确实2-1+4-2的形式,原因是由于2比4小,所以4-1可以分解成2-1+4-2而像第二个数组数组值为5的时候最大的钱为5-1,到了4还是唯5-1=4,原因是5比4大,而4-5为负数,如果加入负数就不是最优解了。