/*List of stock prices are given, find out maximum profit to get by buy and sell in a single transaction
prices = { 23, 28, 5, 6, 18, 15 }
*/
Solution:
prices = { 23, 28, 5, 6, 18, 15 }
*/
Solution:
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for(int price : prices) {
maxProfit = Math.max(maxProfit, price-minPrice);
minPrice = Math.min(minPrice, price);
}
return maxProfit;
}
This can be done in time O(n) with O(1) spaces
No comments:
Post a Comment