703449. Charul and vessels

Easy

Charul and Vessels

Summary

Charul has a set of vessels with different capacities. She wants to fill each vessel with water up to its capacity, but she can't overflow one vessel into another. How many ways are there to fill all the vessels?

This problem involves arrays and dynamic programming concepts.

Detailed Explanation

The key idea is to use dynamic programming to solve this problem. We create a 2D array dp where dp[i][j] represents the number of ways to fill the first i vessels with total capacity j.

Here's the step-by-step breakdown:

  1. Initialize a 2D array dp with dimensions (n+1) x (totalCapacity + 1), where n is the number of vessels and totalCapacity is the sum of their capacities.
  2. Set dp[0][j] = 1 for all j, because there's one way to fill 0 vessels: by not filling any of them.
  3. For each vessel i from 1 to n:
    • For each possible capacity j from 0 to totalCapacity:
      • If the current vessel's capacity is less than or equal to j, then we can either fill it or not. So dp[i][j] = dp[i-1][j] + dp[i-1][j-vesselCapacity].
  4. Return dp[n][totalCapacity], which represents the number of ways to fill all vessels.

Time complexity: O(n * totalCapacity) Space complexity: O(n * totalCapacity)

Here's an ASCII art diagram illustrating the dynamic programming approach:

  +-------+-------+-------+
  | 0    | 1    | 2    |
  +-------+-------+-------+
  |     |     |     |     |
  | 0   | 1   | 2   | 3   |
  +-------+-------+-------+
  |     |     |     |     |
  | 0   | 1   | 2   | 4   |
  +-------+-------+-------+

Optimized Solutions

Java

View on GeeksforGeeks
public int numWays(int n, int[] capacities) {
    int totalCapacity = 0;
    for (int capacity : capacities) {
        totalCapacity += capacity;
    }
    
    int[][] dp = new int[n + 1][totalCapacity + 1];
    for (int i = 0; i <= n; i++) {
        dp[i][0] = 1;
    }
    
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j <= totalCapacity; j++) {
            if (j < capacities[i - 1]) {
                dp[i][j] = dp[i - 1][j];
            } else {
                dp[i][j] = dp[i - 1][j] + dp[i - 1][j - capacities[i - 1]];
            }
        }
    }
    
    return dp[n][totalCapacity];
}

DevExCode

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

© 2026 DevExCode. All rights reserved.