703309. Why is Melody so chocolaty?

Basic

Here is a detailed Markdown blog post for the GeeksforGeeks problem "Why is Melody so chocolaty?":

Why is Melody so chocolaty?

Summary

This problem involves arrays and data structures. We are given an array A of integers, where each element represents the number of chocolates in a bag at that index. Our task is to find out why Melody is so chocolaty by determining the minimum number of bags we need to open to get all the chocolates.

Detailed Explanation

To solve this problem, we will use a simple and efficient algorithm. The idea is to iterate through the array from both ends (beginning and end) and keep track of the total number of chocolates in each half. We stop when the numbers of chocolates in the two halves become equal or when one half becomes empty.

Here's the step-by-step breakdown:

  1. Initialize two variables left and right to represent the total number of chocolates in the left and right halves, respectively.
  2. Initialize a variable min_bags to store the minimum number of bags needed to get all the chocolates.
  3. Iterate through the array from both ends:
    • For each bag, add its chocolate count to either left or right.
    • If left == right, we have found the balance point, and we can stop.
  4. Update min_bags with the minimum of left and right. This represents the minimum number of bags needed to get all the chocolates.

Time complexity: O(n), where n is the size of the array. Space complexity: O(1), as we only use a few variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int minBags(int[] A) {
    int left = 0, right = 0;
    int minBags = Integer.MAX_VALUE;
    
    for (int i = 0; i < A.length; i++) {
        if (i <= A.length / 2) {
            left += A[i];
        } else {
            right += A[A.length - i - 1];
        }
        
        if (left == right) {
            return Math.min(left, right);
        } else if (Math.abs(left - right) > minBags) {
            minBags = Math.abs(left - right);
        }
    }
    
    return minBags;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.