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.
Subscribe to see which companies asked this question
public class Solution {
public int maxProfit(int[] prices) {
//make decision for extreme conditions
if(prices.length==0 || prices == null)
return 0;
int profit=0, min=Integer.MAX_VALUE;
for(int i:prices){
min=(i < min)?i:min;
profit= (i-min)>profit ?(i-min):profit;
}
return profit;
}
}