121. Best Time to Buy and Sell Stock
Asked at 81Meta84Amazon84Bloomberg84Apple80Microsoft78Google72Tesla93HCL89Accenture88Zoho88IBM87Nvidia87tcs80Adobe79Infosys78Siemens75Wipro73Atlassian55Flipkart52Media.net48Millennium100Morgan Stanley100RBC100Sigmoid100Tech Mahindra100Trexquant100Zoox100Akamai94Mastercard94Bank of America93Citigroup92Agoda92Tiger Analytics90Citadel89Garmin89SAP87Toast85Visa84Groww84Comcast83HSBC81Bolt80Airtel77Squarepoint Capital77EPAM Systems77Swiggy77American Express74Uber74Myntra73Cognizant73Optiver71Deloitte71Societe Generale71Remitly70Ozon70NetApp68PayPay68carwale66Expedia65FactSet65BNY Mellon65Turing64PayPal63TikTok63Deutsche Bank62Capgemini62Paytm61Robinhood60ByteDance59Goldman Sachs56Oracle55Walmart Labs53Coinbase51Palo Alto Networks50BlackRock47Cisco45Salesforce45Capital One43Yandex42Snowflake39DE Shaw38
Problem
prices[i] is a stock's price on day i. Buy on one day and sell on a later day; return the maximum profit, or 0 if no profit is possible.
Example: [7,1,5,3,6,4] → 5 (buy at 1, sell at 6); [7,6,4,3,1] → 0
Constraints: n ≤ 10⁵.
Track the cheapest price so far; each day, profit = price − min so far.
Complexity: O(n) time, O(1) space.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
lo, best = float("inf"), 0
for p in prices:
lo = min(lo, p)
best = max(best, p - lo)
return best
assert Solution().maxProfit([7, 1, 5, 3, 6, 4]) == 5
assert Solution().maxProfit([7, 6, 4, 3, 1]) == 0
class Solution {
public int maxProfit(int[] prices) {
int lo = Integer.MAX_VALUE, best = 0;
for (int p : prices) {
lo = Math.min(lo, p);
best = Math.max(best, p - lo);
}
return best;
}
}
func maxProfit(prices []int) int {
lo, best := math.MaxInt, 0
for _, p := range prices {
lo = min(lo, p) // cheapest buy so far
best = max(best, p-lo)
}
return best
}