Dashboard Temp Share Shortlinks Frames API

HTMLify

candy.py
Views: 3 | Author: prakhardoneria
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
    def minCandy(self, arr):
        n = len(arr)
        if n == 0:
            return 0
        
        # Step 1: Initialize everyone with 1 candy
        candies = [1] * n
        
        # Step 2: Left-to-Right Pass
        # Satisfy the condition: higher rating than left neighbor
        for i in range(1, n):
            if arr[i] > arr[i-1]:
                candies[i] = candies[i-1] + 1
        
        # Step 3: Right-to-Left Pass
        # Satisfy the condition: higher rating than right neighbor
        # We use max() to ensure we don't break the Left-to-Right condition
        for i in range(n - 2, -1, -1):
            if arr[i] > arr[i+1]:
                candies[i] = max(candies[i], candies[i+1] + 1)
        
        # Step 4: Return the sum of all candies
        return sum(candies)