DDSA Solutions

Distribute Candies

Time: O(n)
Space: O(n)
Advertisement

Intuition

Distribute minimum candies satisfying neighbor rating constraint. Two-pass greedy.

Algorithm

  1. 1Left pass: if ratings[i] > ratings[i-1]: candies[i] = candies[i-1]+1. Right pass: if ratings[i] > ratings[i+1]: candies[i] = max(candies[i], candies[i+1]+1).

Common Pitfalls

  • Same as LC 135. Two directional passes. Sum of all candies array is the answer.
Distribute Candies.java
Java
// Approach: Count unique candy types. Answer = min(unique types, n/2) where n = total candies.
// Time: O(n) Space: O(n)
class Node {
    int data;
    Node left;
    Node right;

    Node(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}

class Solution {
    
    int ans = 0;
    public int distCandy(Node root) {
        helper(root);
        return ans;
    }

    int helper(Node root) {
        if (root == null)
            return 0;

        int left = helper(root.left);
        int right = helper(root.right);
        ans += Math.abs(left) + Math.abs(right);
        return root.data + left + right - 1;
    }
}
Advertisement
Was this solution helpful?