Created
June 2, 2025 16:38
-
-
Save Ojasvi2005/4693ba0775dc9a5e5616678fb9dbd81e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
LEETCODE CANDY QUESTION | |
QUES NO. 135 | |
Question- | |
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. | |
Mistake I did initially - earlier I was overwriting some values in the second pass. which I fixed later. | |
Example 1: | |
Input: ratings = [1,0,2] | |
Output: 5 | |
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. | |
Example 2: | |
Input: ratings = [1,2,2] | |
Output: 4 | |
Explanation: 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. | |
Constraints: | |
n == ratings.length | |
1 <= n <= 2 * 104 | |
0 <= ratings[i] <= 2 * 104 | |
Solution- | |
class Solution { | |
public: | |
//two pass greedy solution. | |
int candy(vector<int>& ratings) { | |
int n=ratings.size(); | |
if(n==1) return 1; | |
int sum=0; | |
vector<int> temp(n,1); | |
for(int i=1;i<n;i++){ | |
if(ratings[i]>ratings[i-1]){ | |
temp[i]=temp[i-1]+1; | |
} | |
} | |
for(int i=n-2;i>=0;i--){ | |
if(ratings[i]>ratings[i+1]){ | |
temp[i]=max(temp[i],temp[i+1]+1); | |
} | |
sum+=temp[i]; | |
} | |
sum+=temp[n-1]; | |
return sum; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is a C++ code.