`
dugu108
  • 浏览: 23290 次
  • 性别: 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).

 

public class Solution {
    public int maxProfit(int[] prices) {
		// Start typing your Java solution below
		// DO NOT write main() function
		if (prices == null || prices.length <= 0)
			return 0;
		int min = 0;
		int max = 0;
		int result = 0;
		for (int i = 1; i <= prices.length - 1; i++) {
			if (prices[i] > prices[max]) {
				max = i;
			}else {
				result += prices[max] - prices[min];
				max = i;
				min = i;
			}
		}
		result += prices[max] - prices[min];
		return result;
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics