135 - Candy
정보
- 문제 보기: 135 - Candy
- 소요 시간: 51분
- 풀이 언어:
java
- 체감 난이도: 3️⃣
- 리뷰 횟수: ✅
풀이 키워드
스포주의
그리디
풀이 코드
정보
- 메모리: 45700 KB
- 시간: 2 ms
class Solution {
public int candy(int[] ratings) {
// check continuous asc/desc rating order
int n = ratings.length;
int ans = n;
int asc[] = new int[n];
int desc[] = new int[n];
int v = 0;
for (int i = 1; i < n; ++i) {
asc[i-1] = v;
if (ratings[i-1] < ratings[i]) ++v;
else v = 0;
}
asc[n-1] = v;
v = 0;
for (int i = n-1; 0 < i; --i) {
desc[i] = v;
if (ratings[i-1] > ratings[i]) ++v;
else v = 0;
}
desc[0] = v;
for (int i = 0; i < n; ++i) {
ans += Math.max(asc[i], desc[i]);
}
return ans;
}
}
풀이 해설
rating이 인접 칸보다 높으면 반드시 사탕을 더 받게끔 하면서
배분된 총 사탕 개수는 최소로 만들어야 하는 문제이다.
이번에도 어김없는 말장난
문제를 잘 읽자
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.
더 높은 rating일 경우라고 명시했고, 같은 rating에 대해선 아무 언급이 없다.
없으면 뭐다? 해당 제약의 대상이 아니라는 것이다.