Leetcode: 135. Candy

Problem Statement

from typing import List


class Solution:
    def candy(self, r: List[int]) -> int:
        N = len(r)
        low = [1] * N

        ans = 0
        for v, i in sorted(zip(r, range(N))):
            c = []
            if i - 1 >= 0 and r[i - 1] < v:
                c.append(low[i - 1] + 1)
            if i + 1 < N and r[i + 1] < v:
                c.append(low[i + 1] + 1)
            if c:
                low[i] = max(c)
            ans += low[i]

        return ans


assert Solution().candy([1, 0, 2]) == 5
assert Solution().candy([1, 2, 2]) == 4
from typing import List


class Solution:
    def candy(self, r: List[int]) -> int:
        N = len(r)

        cand = [1] * N
        for i in range(1, N):
            if r[i] > r[i - 1]:
                cand[i] = cand[i - 1] + 1

        for i in range(N - 2, -1, -1):
            if r[i] > r[i + 1]:
                cand[i] = max(cand[i], cand[i + 1] + 1)

        return sum(cand)


assert Solution().candy([1, 0, 2]) == 5
assert Solution().candy([1, 2, 2]) == 4