/135. Minimum Candies Distribution Based on Ratings

135. Minimum Candies Distribution Based on Ratings

Hard
Arrays48.1% acceptance

Given an integer array rating_values of length n, assign each element at least one unit. If rating_values[i] > rating_values[i-1], then the unit count at index i must be greater than at index i-1. Similarly, if rating_values[i] > rating_values[i+1], then the unit count at index i must be greater than at index i+1. Return the minimum total units required to satisfy these conditions.

Example 1

Input: [3, 4, 2, 1]

Output: 7

Explanation: Units: [1,2,2,2]

Example 2

Input: [5, 3, 3, 4, 2]

Output: 7

Explanation: Units: [2,1,1,2,1]

Constraints

  • 1 <= len(rating_values) <= 20000
  • 0 <= rating_values[i] <= 20000
Python (current runtime)

Case 1

Input: [2, 2, 1, 3]

Expected: 6

Case 2

Input: [1, 3, 2, 2, 1]

Expected: 7

Case 3

Input: [4, 6, 4, 6, 4, 6]

Expected: 10

Case 4

Input: [10]

Expected: 1

Case 5

Input: [2, 1, 2]

Expected: 4