Create Sorted Array through Instructions
You build a sorted array by inserting the elements of instructions one at a time. The cost of inserting instructions[i] is the minimum of (the count of elements already placed that are strictly less than instructions[i]) and (the count of elements already placed that are strictly greater than instructions[i]). After paying the cost you insert the element in sorted position. Return the total cost of all insertions modulo 10^9 + 7.
Open official problem prompt ↗Sum, over every insertion, the smaller of the count of already-placed smaller elements and already-placed larger elements, modulo 10^9 + 7.
Imagine seating guests on a bench in numbered seats by their ticket number. As each guest arrives you look at how many are already seated to their left versus their right and walk in from whichever side is shorter; the walking distance is the cost, and a Fenwick tree is your fast tally of who is seated where.
- Input
- instructions = [1, 5, 6, 2]
- Output
- 1
- Why
- Costs are 0 (insert 1), 0 (insert 5, nothing greater), 0 (insert 6), and min(1 less, 2 greater) = 1 for inserting 2; total 1.
1 <= instructions.length <= 10^51 <= instructions[i] <= 10^5