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.
Analysis:
1. Track the minimum value which has been encountered currently andthe maximum value of the profit.
2. Each time a new value encountered, the maximum value it can obtain should be new_value - minimum_value. This result should be compared with maximum profit.
Update 12/01/2014:
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length<=1) return 0;
int min = prices[0];
int profit = 0;
for(int i=1; i<prices.length; i++) {
if(prices[i]-min>profit) profit=prices[i]-min;
if(prices[i]<min) min=prices[i];
}
return profit;
}
}
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1) {
return 0;
}
int min = prices[0];
int profit = 0;
for(int i=1; i<prices.length; i++) {
if(prices[i] - min > profit) {
profit = prices[i] - min;
}
if(prices[i] < min) {
min = prices[i];
}
}
return profit;
}
}