/135. Minimum Candies Distribution Based on Ratings

135. Minimum Candies Distribution Based on Ratings

Hard
Arrays48.1% acceptance

Given an integer array rating_scores of length n, assign each element at least one unit. If rating_scores[i] > rating_scores[i-1], then unit_count[i] > unit_count[i-1]. If rating_scores[i] > rating_scores[i+1], then unit_count[i] > unit_count[i+1]. Return the minimum total units required to satisfy these conditions.

Example 1

Input: [3,2,4,1]

Output: 7

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

Example 2

Input: [5,5,5,5]

Output: 4

Explanation: Units: [1,1,1,1].

Example 3

Input: [2,3,1,4]

Output: 6

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

Constraints

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

Case 1

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

Expected: 9

Case 2

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

Expected: 7

Case 3

Input: [7,6,5,4,3]

Expected: 15

Case 4

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

Expected: 7