DEV Community

Debesh P.
Debesh P.

Posted on • Edited on

135. Candy | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/candy/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/candy/solutions/7439508/most-optimal-solution-ever-beats-200-on-ns6oo


leetcode 135


Solution

class Solution {
    public int candy(int[] ratings) {
        int n = ratings.length;
        int count = 0;
        int[] candies = new int[n];

        for(int i=0; i<n; i++) {
            candies[i] = 1;
        }

        for(int i=1; i<n; i++) {
            if(ratings[i] > ratings[i-1]) {
                candies[i] = candies[i-1] + 1;
            }
        }

        for(int i=n-1; i>0; i--) {
            if(ratings[i-1] > ratings[i]) {
                candies[i-1] = Math.max(candies[i] + 1, candies[i-1]);
            }
            count += candies[i-1];
        }

        return count + candies[n-1];
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)