Longest Profit Duration
Updated
Problem statement
You are given an array prices, where prices[i] is the price of a stock on day i.
A trade buys on day i and sells on a later day j (i < j). It makes a profit when prices[j] > prices[i]; selling at the same price is not a profit. The duration of the trade is j - i days.
Return the longest duration of a trade that makes a profit, or 0 if no trade makes a profit.
Function
longestProfitDuration(prices: int[]) → intExamples
Example 1
prices = [10,7,12,9,2,11,8,1,2]return = 5Buying on day 0 at 10 and selling on day 5 at 11 makes a profit and lasts 5 days. Buying on day 1 at 7 and selling on day 6 at 8 also lasts 5 days. The pairs at least 6 days apart are days (0, 6), (0, 7), (0, 8), (1, 7), (1, 8) and (2, 8), and in each one the selling price (8, 1, 2, 1, 2 and 2) is below the buying price (10, 10, 10, 7, 7 and 12). The answer is 5.
Example 2
prices = [5,4,3,2,1]return = 0The price only falls, so no sale makes a profit. The answer is 0.
Example 3
prices = [4,4,5,4]return = 2Days 0 and 3 are 3 days apart, but both prices are 4, so selling makes no profit. The profitable pairs are day 0 or day 1 to day 2. The longer one, day 0 to day 2, lasts 2 days.
Constraints
1 <= prices.length <= 10^41 <= prices[i] <= 10^5
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
- Predict AnswerAmazon · OA
- Search a Row- and Column-Sorted MatrixByteDance · ONSITE INTERVIEWByteDance interview questions
- First and Last Target Position in a Mountain ArrayGoogle · ONSITE INTERVIEWGoogle interview questions
- 3Sum SmallerSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Peak of an Increasing-Then-Decreasing ArraySnap Inc. · ONSITE INTERVIEWSnap Inc. interview questions
- Online Meeting Scheduler with Fixed RoomsUber · ONSITE INTERVIEWUber interview questions
- Compress Editor Actions into Operational Transform OperationsReplit · OA · PHONE SCREEN · ONSITE INTERVIEW
- Flatten a Mixed JSON ListNike, Inc. · ONSITE INTERVIEWNike, Inc. interview questions
- Kth Closest Element in a BSTLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- Trace Events from Stable Whole-Stack StatesAnthropic · ONSITE INTERVIEWAnthropic interview questions