Open In App

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

Last Updated : 29 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Return sum of elements in A[0..N-1]
// using recursion.
bool isPartialSum(int A[], int i, int N, int K)
{
    // Base case: if current sum == K
    if (K == 0)
        return true;
 
    // Edge Case: if current element is the
    // last element
    if (i == N - 1)
 
        // If the remaining sum == last element,
        // then the required partial sum
      // is acheived
        return (A[i] == K);
 
    // Choice 1: Include current element in
    // partial sum
    int take = isPartialSum(A, i + 1, N, K - A[i]);
    // Choice 2: Exclude current element in
    // partial sum
    int notTake = isPartialSum(A, i + 1, N, K);
 
    return take || notTake;
}
 
// Driver code
int main()
{
    int A[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(A) / sizeof(A[0]);
    int K = 6;
   
  // Function Call
    cout << std::boolalpha << isPartialSum(A, 0, N, K)
         << endl;
    return 0;
}


Java




import java.util.Arrays;
 
public class PartialSum {
    // Return true if there is a subset of A[] with sum K
    public static boolean isPartialSum(int[] A, int i,
                                       int N, int K)
    {
        // Base case: if current sum == K
        if (K == 0) {
            return true;
        }
 
        // Edge Case: if current element is the last element
        if (i == N - 1) {
            // If the remaining sum == last element,
            // then the required partial sum is achieved
            return (A[i] == K);
        }
 
        // Choice 1: Include the current element in the
        // partial sum
        boolean take = isPartialSum(A, i + 1, N, K - A[i]);
 
        // Choice 2: Exclude the current element in the
        // partial sum
        boolean notTake = isPartialSum(A, i + 1, N, K);
 
        return take || notTake;
    }
 
    public static void main(String[] args)
    {
        int[] A = { 1, 2, 3, 4, 5 };
        int N = A.length;
        int K = 6;
 
        // Function Call
        System.out.println(isPartialSum(A, 0, N, K));
    }
}


Python3




#Python3 code for the above approach:
 
# Return sum of elements in A[0..N-1] using recursion
def is_partial_sum(A, i, N, K):
    # Base case: if current sum == K
    if K == 0:
        return True
 
    # Edge Case: if current element is the
    # last element
    if i == N - 1:
        # If the remaining sum == last element,
        # then the required partial sum is achieved
        return (A[i] == K)
 
    # Choice 1: Include current element in
    # partial sum
    take = is_partial_sum(A, i + 1, N, K - A[i])
 
    # Choice 2: Exclude current element in
    # partial sum
    not_take = is_partial_sum(A, i + 1, N, K)
 
    return take or not_take
 
 
def main():
    A = [1, 2, 3, 4, 5]
    N = len(A)
    K = 6
 
    # Function Call
    print(is_partial_sum(A, 0, N, K))
 
 
if __name__ == '__main__':
    main()
# This code is contributed by Rohit Singh


C#




//C# code for the above approach:
 
using System;
 
class MainClass
{
    // Return sum of elements in A[0..N-1] using recursion.
    static bool IsPartialSum(int[] A, int i, int N, int K)
    {
        // Base case: if current sum == K
        if (K == 0)
            return true;
 
        // Edge Case: if current element is the
        // last element
        if (i == N - 1)
        {
            // If the remaining sum == last element,
            // then the required partial sum is achieved
            return (A[i] == K);
        }
 
        // Choice 1: Include current element in partial sum
        bool take = IsPartialSum(A, i + 1, N, K - A[i]);
 
        // Choice 2: Exclude current element in partial sum
        bool notTake = IsPartialSum(A, i + 1, N, K);
 
        return take || notTake;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int[] A = { 1, 2, 3, 4, 5 };
        int N = A.Length;
        int K = 6;
 
        // Function Call
        Console.WriteLine(IsPartialSum(A, 0, N, K));
    }
}


Javascript




// Function to check if there exists a subset with the given sum using recursion
function isPartialSum(A, i, N, K) {
    // Base case: if current sum == K
    if (K === 0) {
        return true;
    }
 
    // Edge Case: if current element is the last element
    if (i === N - 1) {
        // If the remaining sum == last element,
        // then the required partial sum is achieved
        return A[i] === K;
    }
 
    // Choice 1: Include the current element in the partial sum
    const take = isPartialSum(A, i + 1, N, K - A[i]);
 
    // Choice 2: Exclude the current element in the partial sum
    const notTake = isPartialSum(A, i + 1, N, K);
 
    return take || notTake;
}
 
// Driver code
function main() {
    const A = [1, 2, 3, 4, 5];
    const N = A.length;
    const K = 6;
 
    // Function call
    console.log(isPartialSum(A, 0, N, K));
}
 
// Run the main function
main();


Output

true








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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads