`
hcx2013
  • 浏览: 88806 次
社区版块
存档分类
最新评论

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).

 

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length <= 1) {
        	return 0;
        }
        int i = 0;
        int res = 0;
        while (i < prices.length-1) {
        	while (i+1<prices.length && prices[i+1]<prices[i]) {
        		i++;
        	}
        	int buy = i;
        	i++;
        	while (i<prices.length && prices[i]>prices[i-1]) {
        		i++;
        	}
        	int sell = i-1;
        	res += prices[sell]-prices[buy];
        }
        return res;
    }
}

 

0
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics