121. Best Time to Buy and Sell Stock
- Amazon, Facebook, Bloomberg, Microsoft, Apple, Google, ...
- Array, Dynamic Programming
- Similar Questions:
Key Points:
- Use a variable to track and store the minimum price.
- 从头到尾遍历整个 array,如果 curr price 小于 previous min price,则说明不能卖掉,因为 previous min price 是买入价格,如果比买入价格 小的话,则说明亏损。所以当遇到比 previous min price 小的 price 就更新 min price。
- 当遇到比 min price 大的价格,就可以选择卖出,更新可获得的最大利润。
class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length<2) {
return 0;
}
int minPrice = Integer.MAX_VALUE;
int maxProfit = Integer.MIN_VALUE;
for(int price: prices) {
if(price < minPrice) {
minPrice = price;
} else {
maxProfit = Math.max(maxProfit, price - minPrice);
}
}
return (maxProfit == Integer.MIN_VALUE) ? 0 : maxProfit;
}
}
Complexity Analysis
- Time complexity : O(n). Only a single pass is needed.
- Space complexity : O(1). Only two variables are used.