Best Time to Buy and Sell Stock
Updated
Problem statement
You are given an array prices, where prices[i] is the price of a stock on day i.
You may buy one share on one day and sell it on a later day, at most once. Return the largest profit you can make. If no trade makes money, return 0.
Function
maxProfit(prices: int[]) → intExamples
Example 1
prices = [8,3,6,2,9,4]return = 7Buy on day 3 at price 2 and sell on day 4 at price 9 for a profit of 7. No other pair of days does better: buying at 3 and selling at 9 gives 6.
Example 2
prices = [9,7,4,1]return = 0The price only falls, so every sale would lose money. Not trading gives 0.
Example 3
prices = [5]return = 0With one day there is no later day to sell on, so the answer is 0.
Constraints
1 <= prices.length <= 10^40 <= prices[i] <= 10^4
More Microsoft Onsite Interview questions
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
- Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
- Smallest Batch Size Within a Step LimitONSITE INTERVIEW · Seen Nov 2026
- Count Subarrays with Equal Even and Odd CountsONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Rot All OrangesONSITE INTERVIEW · Seen Nov 2026
- Coin ChangeONSITE INTERVIEW · Seen Oct 2026
- Daily USD Totals with Effective-Dated Exchange RatesONSITE INTERVIEW · Seen Oct 2026
- Number Words to Digits in Any LanguageONSITE INTERVIEW · Seen Oct 2026
- Totals from a Tiered Rate TableONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Best Time to Buy and Sell StockKotak Mahindra Bank · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Best Time to Buy and Sell StockAmazon · ONSITE INTERVIEW
- Best Time to Buy and Sell StockOracle · PHONE SCREEN · ONSITE INTERVIEWOracle interview questions
- Maximum SubarraySquarepoint Capital · ONSITE INTERVIEWSquarepoint Capital interview questions
- Best Time to Buy and Sell StockZoox · ONSITE INTERVIEW
- Maximum Subarray SumSafe Security · ONSITE INTERVIEW
- Pascal's TriangleEricsson · ONSITE INTERVIEWEricsson interview questions
- Best Time to Buy and Sell StockMotive · ONSITE INTERVIEWMotive interview questions
- Best Time to Buy and Sell StockBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Maximum Profit with Repeated Stock TradesPalantir · ONSITE INTERVIEWPalantir interview questions