Created
June 2, 2025 14:30
-
-
Save SuryaPratapK/f165ee285cf6a2b8d7cc2445a78f6a02 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
class Solution { | |
public: | |
int candy(vector<int>& ratings) { | |
int n=ratings.size(); | |
vector<int> candies(n,1); | |
//Step-1: Assign increasing curve with increasing candies | |
for(int i=1;i<n;++i){ | |
if(ratings[i]>ratings[i-1]) | |
candies[i] = 1 + candies[i-1]; | |
} | |
//Step-2: Assign decreasing curve with increasing candies | |
int total = candies[n-1]; | |
for(int i=n-1;i>0;--i){ | |
if(ratings[i-1]>ratings[i]) | |
candies[i-1] = max(candies[i-1],1+candies[i]); | |
total += candies[i-1]; | |
} | |
return total; | |
} | |
}; | |
/* | |
//JAVA | |
import java.util.Arrays; | |
class Solution { | |
public int candy(int[] ratings) { | |
int n = ratings.length; | |
int[] candies = new int[n]; | |
Arrays.fill(candies, 1); | |
// Step-1: Assign increasing curve with increasing candies | |
for (int i = 1; i < n; ++i) { | |
if (ratings[i] > ratings[i-1]) { | |
candies[i] = 1 + candies[i-1]; | |
} | |
} | |
// Step-2: Assign decreasing curve with increasing candies | |
int total = candies[n-1]; | |
for (int i = n-1; i > 0; --i) { | |
if (ratings[i-1] > ratings[i]) { | |
candies[i-1] = Math.max(candies[i-1], 1 + candies[i]); | |
} | |
total += candies[i-1]; | |
} | |
return total; | |
} | |
} | |
#Python | |
class Solution: | |
def candy(self, ratings: List[int]) -> int: | |
n = len(ratings) | |
candies = [1] * n | |
# Step-1: Assign increasing curve with increasing candies | |
for i in range(1, n): | |
if ratings[i] > ratings[i-1]: | |
candies[i] = 1 + candies[i-1] | |
# Step-2: Assign decreasing curve with increasing candies | |
total = candies[-1] | |
for i in range(n-1, 0, -1): | |
if ratings[i-1] > ratings[i]: | |
candies[i-1] = max(candies[i-1], 1 + candies[i]) | |
total += candies[i-1] | |
return total | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment