Skip to the code
cf.
+50 XP

#95 Later Cheaper Prices

hard

A price-history chart shows, for each day, how many later days had a strictly lower price, to tell shoppers whether waiting usually pays off. The daily prices are in prices.

Write laterCheaper(prices) that returns an array where item i is the number of indexes j > i with prices[j] < prices[i]. Aim for O(n log n) time.

Example 1

Input: prices = [8,3,9,3,1]
Output: [3,1,2,1,0]

After 8 come 3, 3, and 1, all cheaper. After the first 3, only 1 is cheaper (the other 3 is equal, not lower).

Example 2

Input: prices = [1,2,3]
Output: [0,0,0]

Prices only go up, so no later day is cheaper.

Constraints

  • 0 <= prices.length <= 10^5
  • -10^9 <= prices[i] <= 10^9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).