首页 > 其他 > 详细

LeetCode | Best Time to Buy and Sell Stock

时间:2014-02-24 15:29:28      阅读:313      评论:0      收藏:0      [点我收藏+]

题目

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.

分析

遍历一遍数组,遍历过程中,始终记录最小值,即遍历到当前节点所能看到的最佳买入价格。当被遍历节点不是最小值时,计算其与最小值的差价,从而判断是否有最大收益。

代码

public class BestTimeToBuyAndSellStock {
	public int maxProfit(int[] prices) {
		if (prices == null || prices.length <= 1) {
			return 0;
		}

		int profit = 0;
		int min = prices[0];
		for (int i = 1; i < prices.length; ++i) {
			if (prices[i] <= min) {
				min = prices[i];
			} else {
				profit = Math.max(profit, prices[i] - min);
			}
		}
		return profit;
	}
}


LeetCode | Best Time to Buy and Sell Stock

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

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