Best Time to Buy and Sell Stock
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.
思路: 维护两个变量, min 和 profit. min 的初试值为f[0], 从f[1]开始, 逐个更新profit 和 min.
时间复杂度: O(n)
空间复杂度: O(1)public class Solution { public int maxProfit(int[] prices) { //只维持最小值和profit. if (prices.length < 2) { return 0; } int min = prices[0]; int profit = 0; for (int i = 1; i < prices.length; i++) { profit = Math.max(profit, prices[i] - min); min = Math.min(min, prices[i]); } return profit; }}