Candy

This page explains Java solution to problem Candy using Array data structure.

Problem Statement

There are N children standing in a line. Each child is assigned a rating value.

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.

What is the minimum candies you must give?

Example 1:

Input: [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: A = [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.

Solution

If you have any suggestions in below code, please create a pull request by clicking here.

package com.vc.hard;

import java.util.*;

class Candy {
    public int candy(int[] ratings) {
        if(ratings == null) return 0;

        int n = ratings.length;

        int[] left = new int[n];
        Arrays.fill(left, 1);
        for(int i = 1; i < n; i++) {
            int leftElement = ratings[i - 1];
            int currentElement = ratings[i];
            if(leftElement < currentElement) left[i] = left[i - 1] + 1;
        }

        int[] right = new int[n];
        Arrays.fill(right, 1);
        for(int i = n - 2; i >= 0; i--) {
            int rightElement = ratings[i + 1];
            int currentElement = ratings[i];
            if(rightElement < currentElement) right[i] = right[i + 1] +  1;
        }

        int res = 0;
        for(int i = 0; i < n; i++) res += Math.max(left[i], right[i]);

        return res;
    }
}

Time Complexity

O(N) Where
N is total number of children standing in a line

Space Complexity

O(N) Where
N is total number of children standing in a line