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

Best Time to Buy and Sell Stock

时间:2015-01-22 21:58:49      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:leetcode   单调递增   算法   java   

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


Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.


思路:

(1)题意为给定一个数组,数组中第i个元素的值对应着第i天的股票,求只进行一次交易,即买入一次并卖出,所能得到的最大利润。

(2)该题考查的是最大差值。对于本题,如果第i天的值大于第i+1天的值,呈现单调递减就不能买;只有第i天的值小于第i+1天的值,呈现单调递增时买才能获利。所以,遍历数组,分别比较其中相邻的元素之差,获得的最大值即为最大利润。

(3)希望本文对你有所帮助。


算法代码实现如下:

	/**
	 * @authod liqq
	 */
	public int maxProfit(int[] prices) {
		int len = prices.length;
		if (prices == null || len <= 1)
			return 0;
		int curr = prices[0];
		int profit = 0;
		for (int i = 0; i < len; i++) {
			int nex = prices[i];
			profit = nex - curr > profit ? nex - curr : profit;
			curr = curr < nex ? curr : nex;
		}
		return profit;
	}



Best Time to Buy and Sell Stock

标签:leetcode   单调递增   算法   java   

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

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