Min Rewards
Min Rewards
Category
Arrays
Difficulty
Hard
Problem Statement
Imagine a row of students standing in a line, each with a unique score. You need to give rewards (positive integers) to each student such that:
- Every student receives at least 1 reward.
- Any student with a higher score than an adjacent student must receive more rewards than that neighbor.
Return the minimum total number of rewards you must give.
Intuition
The constraints are local: each student only needs to compare with immediate neighbors. If we process the array in two passes — one left-to-right and one right-to-left — we can satisfy both neighbor constraints independently and then take the maximum at each position. The left-to-right pass ensures that each student with a higher score than their left neighbor gets more rewards. The right-to-left pass ensures the same for the right neighbor. Taking the max of both passes satisfies both constraints simultaneously.
Approach
- Initialize a
rewardsarray of length n, all set to 1. - Left-to-right pass: For
ifrom 1 to n-1, ifscores[i] > scores[i-1], setrewards[i] = rewards[i-1] + 1. - Right-to-left pass: For
ifrom n-2 down to 0, ifscores[i] > scores[i+1], setrewards[i] = max(rewards[i], rewards[i+1] + 1). - Return the sum of the
rewardsarray.
Pseudocode
function minRewards(scores):
rewards = array of length(scores) filled with 1
// Left to right pass
for i from 1 to length(scores) - 1:
if scores[i] > scores[i - 1]:
rewards[i] = rewards[i - 1] + 1
// Right to left pass
for i from length(scores) - 2 down to 0:
if scores[i] > scores[i + 1]:
rewards[i] = max(rewards[i], rewards[i + 1] + 1)
return sum(rewards)
Time & Space Complexity
- Time: O(n) — Two linear passes through the array plus a final summation.
- Space: O(n) — For the rewards array.
Key Insights
- The two-pass technique is a common pattern for problems with bidirectional local constraints (also seen in "candy distribution" problems).
- Using
maxin the second pass is essential: we must not reduce a reward that was already set higher by the first pass. - An alternative approach uses local minima (valleys) and expands outward from each valley, but the two-pass method is simpler to implement.
Edge Cases
- Single student: the answer is 1.
- Strictly increasing scores: rewards are
[1, 2, 3, ..., n], totalingn*(n+1)/2. - Strictly decreasing scores: same total as strictly increasing.
- All same scores: not applicable since the problem states scores are unique.
- V-shaped scores (decreasing then increasing): the valley gets 1 reward, and both sides increase outward.