Skip to content

Commit 20ee2bc

Browse files
Merge pull request #1570 from CodingTestStudy2/최원준
[최원준] Day06
2 parents 1188f7d + a5b43ee commit 20ee2bc

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

leetcode3/최원준/135. Candy.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#
2+
3+
'''
4+
Approach1:
5+
1. 아이디어 :
6+
- 작은 숫자부터 채운다.
7+
- 숫자들의 인덱스들을 저장한다.
8+
- 작은 숫자들을 순회하면서 양쪽 rating 값과, candy 값을 바탕으로 최소 candy 값을 구한다.
9+
10+
2. 시간복잡도 :
11+
O(n + n + nlogn + n + n)
12+
13+
3. 자료구조/알고리즘 :
14+
해시맵, 해시셋
15+
16+
Approach2:
17+
1. 아이디어 :
18+
- 왼쪽에서 한번, 오른쪽에서 한번 계산한다.
19+
20+
2. 시간복잡도 :
21+
O(n + n + n + n)
22+
23+
3. 자료구조/알고리즘 :
24+
-
25+
26+
'''
27+
28+
from collections import defaultdict
29+
from typing import List
30+
31+
from typing import List
32+
33+
class Solution:
34+
def candy(self, ratings: List[int]) -> int:
35+
n = len(ratings)
36+
candies = [0] * n
37+
indexes = defaultdict(list)
38+
39+
for i, rating in enumerate(ratings):
40+
indexes[rating].append(i)
41+
42+
sorted_ratings = sorted(set(ratings))
43+
44+
def get_min_candy(rating, index):
45+
value = 1
46+
47+
if index - 1 >= 0 and ratings[index - 1] < rating:
48+
value = max(value, candies[index - 1] + 1)
49+
50+
if index + 1 < n and ratings[index + 1] < rating:
51+
value = max(value, candies[index + 1] + 1)
52+
53+
return value
54+
55+
for rating in sorted_ratings:
56+
for index in indexes[rating]:
57+
candies[index] = get_min_candy(rating, index)
58+
59+
return sum(candies)
60+
61+
def candy2(self, ratings: List[int]) -> int:
62+
n = len(ratings)
63+
candies = [1] * n
64+
65+
for i in range(1, n):
66+
if ratings[i] > ratings[i - 1]:
67+
candies[i] = candies[i - 1] + 1
68+
69+
for i in range(n - 2, -1, -1):
70+
if ratings[i] > ratings[i + 1]:
71+
candies[i] = max(candies[i], candies[i + 1] + 1)
72+
73+
return sum(candies)

0 commit comments

Comments
 (0)