Total Cost Against the Lowest Earlier Price
Updated
Problem statement
You are given an integer array prices. Each index has a cost:
- The cost of index
0isprices[0]. - For every
i >= 1, the cost of indexiisprices[i]minus the smallest value amongprices[0], prices[1], ..., prices[i - 1].
Return the sum of the costs of all indexes from 0 to n - 1, where n is the length of prices.
A cost is negative when prices[i] is smaller than every earlier price. Add it to the sum as it is. The sum can be larger than a 32-bit integer can hold.
Function
totalCost(prices: int[]) → longExamples
Example 1
prices = [5,3,8,6,2,7]return = 15- Index 0 costs
5. - Index 1: the lowest earlier price is
5, so the cost is3 - 5 = -2. - Index 2: the lowest earlier price is
3, so the cost is8 - 3 = 5. Index 3 costs6 - 3 = 3. - Index 4 costs
2 - 3 = -1, and index 5 costs7 - 2 = 5. - The total is
5 - 2 + 5 + 3 - 1 + 5 = 15.
Example 2
prices = [4]return = 4There is only index 0, so the total is its price, 4.
Example 3
prices = [1,1000000000,1000000000,1000000000]return = 2999999998- Index 0 costs
1, and the lowest earlier price stays1for every later index. - Each of the other three indexes costs
1000000000 - 1 = 999999999. - The total is
1 + 3 * 999999999 = 2999999998, which is too large for a 32-bit integer.
Constraints
1 <= prices.length <= 4 * 10^41 <= prices[i] <= 10^9
More PayPal interview questions
- Minimum Cost to Merge Values into OneOA · Seen Nov 2026
- Per-User Sliding-Window Rate LimiterOA · Seen Nov 2026
- Items Purchase (For Java Backend Engineer)OA · Seen Nov 2024
- Find Minimum Price to SpendOA · Seen Oct 2024
- Modify ArrayOA · Seen Jun 2024
- Count User Logins 🌿 (Singapore)OA · Seen Mar 2024
- Similar Password 🪴 (Singapore)OA · Seen Mar 2024
- Can the Singer Perform the Song?PHONE SCREEN · Seen Jul 2025
Similar questions at other companies
- Count Valid Square PairsAuxoAI · OA
- Picked Player Who LostSusquehanna International Group (SIG) · OASusquehanna International Group (SIG) interview questions
- Server InvestmentRippling · OARippling interview questions
- Basic Item DiscountsPalantir · OAPalantir interview questions
- Next Pascal Row CoefficientIntuit · OAIntuit interview questions
- Unique Integers That Sum to ZeroNVIDIA · OANVIDIA interview questions
- Count Multiples of Three with Two SevensHudson River Trading · OAHudson River Trading interview questions
- Diagonal Bounce TraversalAutodesk · OAAutodesk interview questions
- Maximum Student-Teacher DistanceChubb · OAChubb interview questions
- Maximum Three-Server Difficulty ScoreVisa · OAVisa interview questions