O(n) time O(1) space one pass solution

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public int maxProfit(int[] prices) {
int min = Integer.MAX_VALUE, profit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < min) {
min = prices[i];
} else {
profit = Math.max(profit, prices[i] - min);
}
}
return profit;
}
}