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).
可以多次买入卖出,求出最大利润。
由于可以多次买入卖出,所以每次遇到有利润都可以卖出,所以一直循环然后能交易就交易就可以了。
public class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if( len < 2)
return 0;
int result = 0;
int start = 0;
while( start < len ){
start = getStart(prices,start);
if( start == len-1)
break;
result+=(prices[start+1]-prices[start]);
start++;
}
return result;
} public int getStart(int[] prices,int start){
int buy = prices[start];
while( start < prices.length ){
if( buy >= prices[start]){
buy = prices[start];
start++;
}else
break;
}
return start-1; }
}