반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 135 | Candy | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/candy/
문제
There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.
You are giving candies to these children subjected to the following requirements:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
Return the minimum number of candies you need to have to distribute the candies to the children.
조건
- n == ratings.length
- 1 <= n <= 2 * $10^4$
- 0 <= ratings[i] <= 2 * $10^4$
내 풀이
양쪽의 아이들보다 숫자가 큰 아이는 사탕을 더 많이 가져야한다.
양쪽이라는 말은 앞에서 봐도, 뒤에서 봐도 더 크다는 뜻이 된다.
이를 이용해, 먼저 앞에서부터 쭉 훑으며 숫자가 더 크면 사탕을 더 많이준다.
이어서 뒤에서부터 훑으며 숫자가 더 크면 사탕을 더 많이준다.
코드
class Solution:
def candy(self, ratings: List[int]) -> int:
N = len(ratings)
nums = [1]*N
for n in range(1, N):
if ratings[n-1] < ratings[n]:
nums[n] = nums[n-1] + 1
for n in range(N-1, 0, -1):
if ratings[n-1] > ratings[n]:
nums[n-1] = max(nums[n-1], nums[n] + 1)
return sum(nums)
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 97 | Interleaving String | Python (0) | 2022.07.07 |
---|---|
[LeetCode] 509 | Fibonacci Number | Python (0) | 2022.07.06 |
[LeetCode] 1710 | Maximum Units on an Truck | Python (0) | 2022.07.01 |
[LeetCode] 406 | Queue Reconstruction by Height | Python (0) | 2022.06.29 |
[LeetCode] 1647 | Minimum Deletions to Make Character Frequencies Unique | Python (0) | 2022.06.28 |
Comments