Social feed~35 min4s · 256 MBtarget O(n log n) time, O(n) spacefenwick-tree
You work on a social feed. A trending list shows posts in the order they were published, and each post has an engagement score. Editors look for "slides": three posts, published one after another, whose scores fall at every step.
Your team lead asks: "How many slides does the list contain?" A slide is any three posts, not only neighbours, published in this order with scores that are strictly lower each time. The list can hold 100,000 posts.
Write count_slides(scores).
scores[i] is the engagement score of the post published in position i.i < j < k with scores[i] > scores[j] > scores[k].Input: scores = [5, 3, 4, 2, 1]
Output: 7For each post as the middle of a slide, count the earlier posts with a higher score and the later posts with a lower score.
| Position | Score | Earlier and higher | Later and lower | Slides with this middle post |
|---|---|---|---|---|
| 0 | 5 | 0 | 4 | 0 |
| 1 | 3 | 1 | 2 | 2 |
| 2 | 4 | 1 | 2 | 2 |
| 3 | 2 | 3 | 1 | 3 |
| 4 | 1 | 4 | 0 | 0 |
The total is 0 + 2 + 2 + 3 + 0 = 7.
Input: scores = [9, 1]
Output: 0Two posts cannot make a slide of three.
Input: scores = [4, 4, 4, 4]
Output: 0Equal scores never fall, so no triple counts.
1 ≤ len(scores) ≤ 100,0001 ≤ scores[i] ≤ 1,000,000,000There are about 1.7 × 10^14 triples of positions, so no program can look at each one. Even looking at each pair costs 5 billion steps. You need about n log n steps, which is under 2 million. The answer itself can reach 1.7 × 10^14, which does not fit in 32 bits.