Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit7edf80a

Browse files
authored
Merge pull requestneetcode-gh#3359 from hemilpatel971/my-solutions
Create: 0135-candy.py
2 parentsf1c1efd +f3725bd commit7edf80a

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

‎python/0135-candy.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
classSolution:
2+
defcandy(self,ratings:List[int])->int:
3+
n=len(ratings)
4+
# Initialize with one candy becuase each child must have at least one candy.
5+
candies= [1]*n
6+
7+
# Iterate from left to right
8+
foriinrange(1,n):
9+
# Check if current rating is greater than left neighbor
10+
ifratings[i]>ratings[i-1]:
11+
# Rating is higher so deserves more candy than left neighbor
12+
candies[i]=candies[i-1]+1
13+
14+
# Iterate from right to left
15+
foriinrange(n-2,-1,-1):
16+
# Check if current rating is greater than right neighbor
17+
ifratings[i]>ratings[i+1]:
18+
# Take max to check if the value is already greater than its right neighbor + 1.
19+
candies[i]=max(candies[i],candies[i+1]+1)
20+
21+
returnsum(candies)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp