Check if array can be divided into two sub-arrays such that their absolute difference is K

Given an array arr[] and an integer K, the task is to find whether the array can be divided into two sub-arrays such that the absolute difference of the sum of the elements of both the sub-arrays is K.
Examples:Â
Input: arr[] = {2, 4, 5, 1}, K = 0Â
Output: YesÂ
{2, 4} and {5, 1} are the two possible sub-arrays.Â
|(2 + 4) – (5 + 1)| = |6 – 6| = 0Input: arr[] = {2, 4, 1, 5}, K = 2Â
Output: NoÂ
Approach:Â Â
- Assume there exists an answer, let the sum of elements of the sub-array (with smaller sum) is S.
- Sum of the elements of the second array will be S + K.
- And, S + S + K must be equal to sum of all the elements of the array say totalSum = 2 *S + K.
- S = (totalSum – K) / 2
- Now, traverse the array till we achieve a sum of S starting from the first element and if its not possible then print No.
- Else print Yes.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>using namespace std;Â
// Function that return true if it is possible// to divide the array into sub-arrays// that satisfy the given conditionbool solve(int array[], int size, int k){    // To store the sum of all the elements    // of the array    int totalSum = 0;    for (int i = 0; i < size; i++)        totalSum += array[i];Â
    // Sum of any sub-array cannot be    // a floating point value    if ((totalSum - k) % 2 == 1)        return false;Â
    // Required sub-array sum    int S = (totalSum - k) / 2;Â
    int sum = 0;    for (int i = 0; i < size; i++) {        sum += array[i];        if (sum == S)            return true;    }Â
    return false;}Â
// Driver Codeint main(){    int array[] = { 2, 4, 1, 5 };    int k = 2;    int size = sizeof(array) / sizeof(array[0]);    if (solve(array, size, k))        cout << "Yes" << endl;    else        cout << "No" << endl;} |
Java
/*package whatever //do not write package name here */Â
import java.io.*;Â
class GFG {     // Function that return true if it is possible// to divide the array into sub-arrays// that satisfy the given conditionstatic boolean solve(int array[], int size, int k){    // To store the sum of all the elements    // of the array    int totalSum = 0;    for (int i = 0; i < size; i++)        totalSum += array[i];Â
    // Sum of any sub-array cannot be    // a floating point value    if ((totalSum - k) % 2 == 1)        return false;Â
    // Required sub-array sum    int S = (totalSum - k) / 2;Â
    int sum = 0;    for (int i = 0; i < size; i++)     {        sum += array[i];        if (sum == S)            return true;    }    return false;}Â
    // Driver Code    public static void main (String[] args)    {        int array[] = { 2, 4, 1, 5 };        int k = 2;        int size = array.length;                 if (solve(array, size, k))            System.out.println ("Yes");        else            System.out.println ("No" );    }}Â
// This Code is contributed by akt_mit |
Python3
# Function that return true if it is possible# to divide the array into sub-arrays# that satisfy the given conditiondef solve(array,size,k):    # To store the sum of all the elements    # of the array    totalSum = 0    for i in range (0,size):        totalSum += array[i]Â
    # Sum of any sub-array cannot be    # a floating point value    if ((totalSum - k) % 2 == 1):        return FalseÂ
    # Required sub-array sum    S = (totalSum - k) / 2Â
    sum = 0;    for i in range (0,size):        sum += array[i]        if (sum == S):            return True     Â
    return FalseÂ
Â
# Driver Codearray= [2, 4, 1, 5]k = 2n = 4if (solve(array, n, k)):Â Â Â Â print("Yes")else:Â Â Â Â print("No")Â
# This code is contributed by iAyushRaj. |
C#
using System;class GFG{Â
// Function that return true if it is possible// to divide the array into sub-arrays// that satisfy the given conditionpublic static bool solve(int[] array, int size, int k){    // To store the sum of all the elements    // of the array    int totalSum = 0;    for (int i = 0; i < size; i++)        totalSum += array[i];Â
    // Sum of any sub-array cannot be    // a floating point value    if ((totalSum - k) % 2 == 1)        return false;Â
    // Required sub-array sum    int S = (totalSum - k) / 2;Â
    int sum = 0;    for (int i = 0; i < size; i++)     {        sum += array[i];        if (sum == S)            return true;    }Â
    return false;}Â
// Driver Codepublic static void Main(){    int[] array = { 2, 4, 1, 5 };    int k = 2;    int size = 4;         if (solve(array, size, k))        Console.Write("Yes");    else        Console.Write("No");}}Â
// This code is contributed by iAyushRaj. |
PHP
<?php// Function that return true if it is possible// to divide the array into sub-arrays// that satisfy the given conditionfunction solve($array, $size,$k){    // To store the sum of all the elements    // of the array    $totalSum = 0;    for ($i = 0; $i < $size; $i++)        $totalSum += $array[$i];Â
    // Sum of any sub-array cannot be    // a floating point value    if (($totalSum - $k) % 2 == 1)        return false;Â
    // Required sub-array sum    $S = ($totalSum - $k) / 2;Â
    $sum = 0;    for ($i = 0; $i < $size; $i++)     {        $sum += $array[$i];        if ($sum == $S)            return true;    }Â
    return false;}Â
// Driver Code$array = array( 2, 4, 1, 5 );$k = 2;$size = sizeof($array);if (solve($array, $size, $k))    echo "Yes";else    echo "No";Â
// This code is contributed by iAyushRaj.?> |
Javascript
<script>Â
// Javascript program to illustrate // the above problem Â
// Function that return true if it is possible// to divide the array into sub-arrays// that satisfy the given conditionfunction solve(array, size, k){    // To store the sum of all the elements    // of the array    let totalSum = 0;    for (let i = 0; i < size; i++)        totalSum += array[i];Â
    // Sum of any sub-array cannot be    // a floating point value    if ((totalSum - k) % 2 == 1)        return false;Â
    // Required sub-array sum    let S = (totalSum - k) / 2;Â
    let sum = 0;    for (let i = 0; i < size; i++)     {        sum += array[i];        if (sum == S)            return true;    }    return false;}Â
// Driver CodeÂ
        let array = [ 2, 4, 1, 5 ];        let k = 2;        let size = array.length;                 if (solve(array, size, k))            document.write("Yes");        else            document.write ("No" );Â
</script> |
Output
No
Complexity Analysis:
- Time Complexity: O(n) where n is the size of the array.
- Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



