1336. Larger-Left Totals

A stock desk records daily prices in nums. For every day i, the desk wants the combined value of all earlier days j < i whose price was strictly higher than nums[i]. Return an array res of the same length where res[i] is the sum of nums[j] over all j < i with nums[j] > nums[i], and 0 when no such day exists. Equal prices do not count. Sums can pass 32 bits, so return 64-bit integers. A merge sort that carries the original positions, or a Fenwick tree over compressed values, solves it in O(n log n) time.

Example 1

Input:
nums = [5,2,4,1]
Output:
[0,5,5,11]
Explanation:

For the last element 1, the earlier larger values are 5, 2 and 4, which add up to 11.

Example 2

Input:
nums = [1,2,3]
Output:
[0,0,0]
Explanation:

The values only grow, so no earlier value is larger than a later one.

Example 3

Input:
nums = [3,3,3]
Output:
[0,0,0]
Explanation:

Equal values are not strictly larger, so every sum is 0.

Constraints

1 ≤ n ≤ 105

-109 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…