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).
思路:注意本题有上一题的区别,本题是要求你必须卖了才能买,用贪心算法可以解决,买次碰到价高的时候就把他卖了,碰到价低的时候就它买了,比如prices[]={10,8,12,7,5,9} 因为12比8大,那就在8的时候买入,12的时候卖出,profit=4,9又比5大,就在5的时候买入,9的时候卖出,profit=4+4=8;
所以最大利润是8;注意为什么只有prices[i+1]>prices[i]的时候才买入和卖出,因为只有这种情况,才能保证这个局部是获利的并且保证了不会有任意一次交易是亏钱的,并且把握住了每一次赚钱的机会。
代码如下(已通过leetcode)
public class Solution {
public int maxProfit(int[] prices) {
int sum=0;
for(int i=0;i<prices.length-1;i++) {
if(prices[i+1]>prices[i]) sum+=prices[i+1]-prices[i];
}
return sum;
}
}