VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-given-integer-is-whole-or-partial-sum-of-given-array-elements/

⇱ Check if given integer is whole or partial sum of given Array elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if given integer is whole or partial sum of given Array elements

Last Updated : 23 Jul, 2025

Given an integer K and an array A[] of size M, check if it is possible to obtain the integer K by taking the sum of one or more elements from the array A, with each element used at most once.

Examples:

Input: A[] = {1, 2, 3}, K = 6
Output: True
Explanation: 1 + 2 + 3 = 6

Input: A[] = {15, 12, 13, 10}, K = 20
Output: False

Approach: To solve the problem follow the below idea:

The given problem can be solved using the property of recursion, that every array element has 2 choices for the answer:

  1. Either the array element can be included in the current sum to contribute towards K.
  2. Or the array element can be skipped to find the total sum as K.

Steps to solve the problem:

  • Define a recursive function isPartialSum with parameters A, i, N, and K.
  • Base Cases:
    • If K becomes 0, return true.
    • If i reaches the last element (N - 1) and A[i] equals K, return true.
  • Explore Choices:
    • Include the current element A[i] in the partial sum (take) by making a recursive call with i + 1 and K - A[i].
      Exclude the current element (notTake) by making a recursive call with i + 1 and K.
    • Return true if either take or notTake is true, indicating a valid partial sum.
  • In main, initialize the array A, its size N, and the target sum K.
    • Call isPartialSum and print the result as a boolean.

Below is the implementation of the above approach:


Output
true

Time Complexity: O(N), where N is the number of elements in the array.
Auxiliary Space: O(N), Recursive Stack Space

Comment
Article Tags:
Article Tags: