首页 > 其他 > 详细

LeetCode | Best Time to Buy and Sell Stock II

时间:2014-02-24 14:56:37      阅读:336      评论:0      收藏:0      [点我收藏+]

题目

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) {
		if (prices == null || prices.length <= 1) {
			return 0;
		}

		int profit = 0;
		int N = prices.length;
		int j, i = 0;
		while (i < N) {
			// find the valley
			while (i + 1 < N && prices[i] >= prices[i + 1]) {
				++i;
			}
			// find the peak
			j = i + 1;
			while (j + 1 < N && prices[j] < prices[j + 1]) {
				++j;
			}
			if (j < N) {
				profit += prices[j] - prices[i];
			}
			i = j + 1;
		}
		return profit;
	}
}
代码2

public class BestTimeToBuyAndSellStockII {
	public int maxProfit(int[] prices) {
		int profit = 0;
		for (int i = 0; i < prices.length - 1; i++) {
			if (prices[i + 1] > prices[i]) {
				profit += prices[i + 1] - prices[i];
			}
		}
		return profit;
	}
}

LeetCode | Best Time to Buy and Sell Stock II

原文:http://blog.csdn.net/perfect8886/article/details/19764467

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!