码迷,mamicode.com
首页 > 其他好文 > 详细

Best Time to Buy and Sell Stock II

时间:2015-01-26 22:57:31      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:leetcode   单调递增   算法   java   

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/43155725



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)题意为给定一个数组,数组中第i个元素的值对应着第i天的股票,你可以完成多次交易,但是每次交易只能买入一次并卖出,求进行多次交易所能得到的最大利润。该题为Best Time to Buy and Sell Stock的加强版。

(2)与Best Time to Buy and Sell Stock类似,该题同样考查的是最大差值。只不过该题考查数组中所有相邻且递增元素的数值之差的总和。只要第i+1天的值大于第i天的值,则可买入,求得利润(差值),遍历整个数组,得到所用差值之和即为总的利润。

(3)该题还是比较简单。希望对你有所帮助。


算法代码实现如下:

	/**
	 * 
	 * @author liqq
	 */
	public int maxProfit(int[] x) {
		if (x == null || x.length <= 1)
			return 0;

		int min = x[0];
		int profit = 0;

		for (int i = 0; i < x.length; i++) {
			if (min > x[i]) {
				min = x[i];
			} else {
				profit += x[i] - min;
				min = x[i];
			}
		}
		return profit;
	}




Best Time to Buy and Sell Stock II

标签:leetcode   单调递增   算法   java   

原文地址:http://blog.csdn.net/pistolove/article/details/43155725

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!