Leetcode_122_Best Time to Buy and Sell Stock II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pistolove/article/details/43155725

本文是在学习中的总结,欢迎转载但请注明出处: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;
	}




没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试