Best Time to Buy and Sell Stock II

题目描述: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).


1自己的代码
public class BestTimeToBuyandSellStockII {
	public int maxProfit(int[] prices) {
		//找出最后一个升序序列中的最后一个价格的下标
		int len = 0;
		for(int i = prices.length - 1; i > 0; i--){
			if(prices[i] > prices[i-1]) {len =  i; break;} 
		}
		int profits = 0;
		for(int i = 0; i < len; i++){
			if(prices[i + 1] > prices[i]) profits += (prices[i + 1] - prices[i]);
		}
        return profits;
    }
	}

你可能感兴趣的:(time)