题目
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