Best Time to Buy and Sell Stock
Updated
Problem statement
Each entry of prices is the price of one share of a stock on one day: prices[i] is the price on day i.
You may make at most one trade: buy one share on some day, then sell it on a later day. Return the largest profit you can make, where the profit is the sale price minus the purchase price. If no trade makes money, do not trade and return 0.
Function
maxProfit(prices: int[]) → intExamples
Example 1
prices = [4,9,2,6,3,8]return = 6Buy on day 2 at price 2 and sell on day 5 at price 8. The profit is 8 - 2 = 6.
Buying on day 0 at 4 and selling on day 1 at 9 earns only 5.
Example 2
prices = [10,8,8,5,1]return = 0The price never rises from one day to a later day, so every trade loses money or makes nothing. Do not trade and return 0.
Example 3
prices = [5,1,11,0,7]return = 10Buy on day 1 at 1 and sell on day 2 at 11 for a profit of 10.
The lowest price, 0, is on day 3, but the best sale after it is 7, which gives only 7.
Constraints
1 <= prices.length <= 10^40 <= prices[i] <= 10^4
More Meta Phone Screen questions
- Mutual-Friend RecommendationsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First Element Greater Than KPHONE SCREEN · Seen Nov 2026
- Count Events in Rolling Minute WindowsPHONE SCREEN · Seen Oct 2026
- Valid Word AbbreviationPHONE SCREEN · Seen Oct 2026
- Shortest Path in a Binary MatrixPHONE SCREEN · Seen Sep 2026
- Deterministic K-Means AssignmentsPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
- Multi-Head Attention Forward PassPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
- Values Exclusive to the Current UserPHONE SCREEN · Seen Sep 2026
- First Bad Version in a Monotone ArrayPHONE SCREEN · Seen Sep 2026
- Parenthesized String CalculatorPHONE SCREEN · Seen Sep 2026
Similar questions at other companies
- Best Time to Buy and Sell StockSwiggy · PHONE SCREEN
- Suffix Maximum Frequency QueriesMicrosoft · PHONE SCREENMicrosoft interview questions
- Best Time to Buy and Sell StockOracle · PHONE SCREEN · ONSITE INTERVIEWOracle interview questions
- Best Time to Buy and Sell StockJP Morgan Chase · PHONE SCREENJP Morgan Chase interview questions
- Best Time to Buy and Sell StockBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Find Max Length of SubsequenceGoogle · PHONE SCREENGoogle interview questions
- Maximum Subarray Sum with One DeletionServiceNow · PHONE SCREENServiceNow interview questions
- Maximum Product of a Contiguous SubarrayLinkedIn · PHONE SCREENLinkedIn interview questions
- Longest Increasing SubsequenceByteDance · PHONE SCREENByteDance interview questions
- Jump GamePaytm · PHONE SCREENPaytm interview questions