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 Solution {
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
if (prices == null || prices.length <= 0)
return 0;
int min = 0;
int max = 0;
int result = 0;
for (int i = 1; i <= prices.length - 1; i++) {
if (prices[i] > prices[max])
max = i;
if (prices[i] < prices[min]) {
if (i > max) {
if (result < prices[max] - prices[min]) {
result = prices[max] - prices[min];
}
max = i;
}
min = i;
}
}
if (result < prices[max] - prices[min]) {
result = prices[max] - prices[min];
}
return result;
}
}