<p>There are <code>n</code> children standing in a line. Each child is assigned a rating value given in the integer array <code>ratings</code>.</p>

<p>You are giving candies to these children subjected to the following requirements:</p>

<ul>
	<li>Each child must have at least one candy.</li>
	<li>Children with a higher rating get more candies than their neighbors.</li>
</ul>

<p>Return <em>the minimum number of candies you need to have to distribute the candies to the children</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> ratings = [1,0,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> ratings = [1,2,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == ratings.length</code></li>
	<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>0 &lt;= ratings[i] &lt;= 2 * 10<sup>4</sup></code></li>
</ul>

class Solution:
    def candy(self, ratings: List[int]) -> int:
        if len(ratings) == 1:
            return 1
        changes = (-1 if a == b else int(a > b) for a, b in pairwise(ratings))
        changes_rle = [(x, sum(1 for _ in y)) for x, y in groupby(changes)]
        print(changes_rle)
        change, cnt = changes_rle[0]
        if change == -1:
            res = cnt + 1
        else:
            res = (cnt + 1) * (cnt + 2) // 2
        for i in range(1, len(changes_rle)):
            change, cnt = changes_rle[i]
            if change == -1:
                res += cnt
            elif change == 0:
                res += (cnt + 1) * (cnt + 2) // 2 - 1
            else:
                prevchange, prevcnt = changes_rle[i-1]
                if prevchange == -1:
                    res += (cnt + 1) * (cnt + 2) // 2 - 1
                elif prevcnt > cnt:
                    res += cnt * (cnt+1) // 2
                else:
                    res += (cnt + 1) * (cnt + 2) // 2 - prevcnt - 1
        return res
20200