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) {
//int ans = 0;
if(prices.length <= 1) return 0;
int profit = 0;
int min = prices[0];
for (int i = 0; i < prices.length; i++) {
min = Math.min(min, prices[i]);
profit = Math.max(profit, prices[i] - min);
}
return profit;
}
}
The difference between two buy and sell problems is the amount of transactions. This algorithm is really neat.