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.
// Only remember the lowest pricepublicclassSolution {publicintmaxProfit(int[] prices) {if (prices ==null||prices.length==0) {return0; }// Only remember the smallest priceint min =Integer.MAX_VALUE; int profit =0;for (int i : prices) { min = i < min ? i : min; profit = (i - min) > profit ? i - min : profit; }return profit; }}
Reference
Best Time to Buy and Sell Stock Series: I, II, III, IV