1109. Cheapest Line Partition
A school photographer lines up n students in non-decreasing order of height, given by heights. To fit everyone in the frame she splits the line into consecutive rows: every student belongs to exactly one row, and each row is a block of neighbours in the line. Every row costs a fixed booking fee of cost, plus a ragged-edge penalty equal to the square of the difference between the tallest and the shortest student in that row.
Return the smallest possible total cost over all ways to split the line into rows. A row may hold a single student (its penalty is then 0), and the whole line may form a single row.
Example 1
- Input:
- heights = [1,2,3,10,11,12], cost = 5
- Output:
- 18
- Explanation:
Two rows {1,2,3} and {10,11,12} cost (2^2 + 5) twice = 18, while one row of all six would cost 11^2 + 5 = 126.
Example 2
- Input:
- heights = [7], cost = 4
- Output:
- 4
- Explanation:
A single student forms one row with penalty 0, so only the booking fee 4 is paid.
Example 3
- Input:
- heights = [5,5,5,5], cost = 3
- Output:
- 3
- Explanation:
Everyone has the same height, so one row costs just the fee 3, and any further row would add another fee.
Constraints
1 ≤ heights.length ≤ 100000
0 ≤ heights[i] ≤ 50000 and heights is sorted in non-decreasing order
1 ≤ cost ≤ 109
The answer needs a 64-bit integer.
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 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)