Best Time to Buy and Sell Stock
Updated
Problem statement
You are given an array prices, where prices[i] is the price of one share on day i.
You may choose one day to buy one share and a later day to sell that share. Return the maximum profit you can earn. If no profitable transaction exists, return 0.
Function
maxProfit(prices: int[]) → intExamples
Example 1
prices = [7,1,5,3,6,4]return = 5Buy at price 1 and sell later at price 6, for profit 6 - 1 = 5.
Example 2
prices = [7,6,4,3,1]return = 0Every later price is lower, so no profitable transaction exists.
Example 3
prices = [2,4,1]return = 2Buy on the first day at price 2 and sell on the second day at price 4.
Constraints
1 <= prices.length <= 2000000 <= prices[i] <= 1000000000- The returned profit fits in a signed 32-bit integer.
More Zoox Onsite Interview questions
Similar questions at other companies
- Best Time to Buy and Sell StockOracle · PHONE SCREEN · ONSITE INTERVIEWOracle 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
- Best Time to Buy and Sell Stock IIKotak Mahindra Bank · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Minimum Taps to Water a GardenThe D.E. Shaw Group · ONSITE INTERVIEWThe D.E. Shaw Group interview questions
- Maximum Stock Profit with Unlimited TransactionsSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Maximum Stock Profit with Transaction LimitsMeta · ONSITE INTERVIEWMeta interview questions
- Jump Game IITripjack · ONSITE INTERVIEWTripjack interview questions
- First Five Increasing Temperature RangesAmazon · ONSITE INTERVIEW