`
淡淡的一抹
  • 浏览: 19293 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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;
    }
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics