Open In App

Check if sum of exactly K elements of the Array can be odd or not

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array, arr[] and an integer K. Check whether it is possible to get an odd sum by choosing exactly K elements of the array.

Examples: 

Input: arr[] = {1, 2, 3}, K = 2 
Output: Possible 
Explanation: 
{2, 3} ⇾ 2 + 3 = 5

Input: arr[] = {2, 2, 4, 2}, K = 4 
Output: Not Possible 
Explanation: {2, 2, 4, 2} ⇾ 2 + 2 + 4 + 2 = 10 
No other possibilities as K is equal to the size of array 

Approach: On observing, it is found that there are three cases.

  • First, count the number of odd and even elements.
  • Case 1: When all elements are even. Then, sum will always be even irrespective of the value of K as even + even = even.
  • Case 2: When all elements are odd. Then, the sum will depend only on the value of K. 
    If K is odd, then the sum will be odd as every odd pair makes the sum even and in the end, one odd element makes the sum odd as even + odd = odd
    If K is even, then every odd element get paired and become even, therefore the sum becomes even.
  • Case 3: When K <= N, then sum depends only on the number of odd elements. If the number of odd elements is even, then the sum will be even as odd + odd = even, which implies every odd pair will become even. And if we add even elements to the sum, the sum will remain even as even + even = even.

Below is the implementation of the above approach: 

C++




// C++ implementation of the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function returns true if
// it is possible to have
// odd sum
bool isPossible(int arr[],
                int N, int K)
{
    int oddCount = 0, evenCount = 0;
 
    // counting number of odd
    // and even elements
    for (int i = 0; i < N; i++) {
        if (arr[i] % 2 == 0)
            evenCount++;
        else
            oddCount++;
    }
    if (evenCount == N
        || (oddCount == N && K % 2 == 0)
        || (K == N && oddCount % 2 == 0))
        return false;
    else
        return true;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 8 };
    int K = 5;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    if (isPossible(arr, N, K))
        cout << "Possible";
    else
        cout << "Not Possible";
 
    return 0;
}


Java




// Java implementation of the above approach
class GFG{
 
// Function returns true if
// it is possible to have
// odd sum
static boolean isPossible(int arr[],
                          int N, int K)
{
    int oddCount = 0, evenCount = 0;
     
    // Counting number of odd
    // and even elements
    for(int i = 0; i < N; i++)
    {
       if (arr[i] % 2 == 0)
       {
           evenCount++;
       }
       else
       {
           oddCount++;
       }
    }
    if (evenCount == N ||
       (oddCount == N && K % 2 == 0) ||
       (K == N && oddCount % 2 == 0))
    {
        return false;
    }
    else
    {
        return true;
    }
}
     
// Driver code
public static void main (String[] args)
{
    int arr[] = { 1, 2, 3, 4, 5, 8 };
    int K = 5;
    int N = arr.length;
     
    if (isPossible(arr, N, K))
    {
        System.out.println("Possible");
    }
    else
    {
        System.out.println("Not Possible");
    }
}
}
 
// This code is contributed by AnkitRai01


Python3




# Python3 implementation of the above approach
 
# Function returns true if it
# is possible to have odd sum
def isPossible(arr, N, K):
     
    oddCount = 0
    evenCount = 0
 
    # Counting number of odd
    # and even elements
    for i in range(N):
        if (arr[i] % 2 == 0):
            evenCount += 1
        else:
            oddCount += 1
             
    if (evenCount == N or
       (oddCount == N and K % 2 == 0) or
       (K == N and oddCount % 2 == 0)):
        return False
    else:
        return True
 
# Driver code
if __name__ == '__main__':
     
    arr = [ 1, 2, 3, 4, 5, 8 ]
    K = 5
    N = len(arr)
 
    if (isPossible(arr, N, K)):
        print("Possible")
    else:
        print("Not Possible")
 
# This code is contributed by mohit kumar 29   


C#




// C# implementation of the above approach
using System;
 
class GFG{
 
// Function returns true if
// it is possible to have
// odd sum
static bool isPossible(int []arr,
                       int N, int K)
{
    int oddCount = 0, evenCount = 0;
 
    // Counting number of odd
    // and even elements
    for(int i = 0; i < N; i++)
    {
       if (arr[i] % 2 == 0)
       {
           evenCount++;
       }
       else
       {
           oddCount++;
       }
    }
    if (evenCount == N ||
       (oddCount == N && K % 2 == 0) ||
       (K == N && oddCount % 2 == 0))
    {
        return false;
    }
    else
    {
        return true;
    }
}
 
// Driver code
public static void Main (string[] args)
{
    int []arr = { 1, 2, 3, 4, 5, 8 };
    int K = 5;
    int N = arr.Length;
 
    if (isPossible(arr, N, K))
    {
        Console.WriteLine("Possible");
    }
    else
    {
        Console.WriteLine("Not Possible");
    }
}
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
// Javascript implementation of the above approach
 
// Function returns true if
// it is possible to have
// odd sum
function isPossible(arr, N, K)
{
    let oddCount = 0, evenCount = 0;
      
    // Counting number of odd
    // and even elements
    for(let i = 0; i < N; i++)
    {
       if (arr[i] % 2 == 0)
       {
           evenCount++;
       }
       else
       {
           oddCount++;
       }
    }
    if (evenCount == N ||
       (oddCount == N && K % 2 == 0) ||
       (K == N && oddCount % 2 == 0))
    {
        return false;
    }
    else
    {
        return true;
    }
}
 
  // Driver Code
     
    let arr = [ 1, 2, 3, 4, 5, 8 ];
    let K = 5;
    let N = arr.length;
      
    if (isPossible(arr, N, K))
    {
        document.write("Possible");
    }
    else
    {
        document.write("Not Possible");
    }
 
// This code is contributed by target_2.
</script>


Output

Possible





Time complexity: O(N), where N represents the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Method 2:Using Recursion

Approach:

In this approach we create a function isOddSumPossible()  function first tests the base cases when k is zero or the array size is zero, returning true if the current sum is odd and false otherwise. If k is negative, the method returns false since an odd sum is not possible.

If the base cases fail, the function performs two recursive calls: one that includes the current element in the total and reduces the number of elements to pick by one, and another that excludes the current element while keeping the number of elements to choose constant. The function returns true if either of these recursive calls returns true; otherwise, it returns false.

Implementation:

C++




#include <bits/stdc++.h>
using namespace std;
 
bool isOddSumPossible(int arr[], int n, int k, int sum) {
    // If k is zero, check if the sum is odd
    if (k == 0) {
        return (sum % 2 != 0);
    }
    // If n is zero or k is negative, odd sum is not possible
    if (n == 0 || k < 0) {
        return false;
    }
    // Recur by including or excluding the current element
    return isOddSumPossible(arr, n - 1, k - 1, sum + arr[n - 1]) ||
           isOddSumPossible(arr, n - 1, k, sum);
}
 
int main() {
    int arr[]={1,2,3,4,5,8};
    int K = 5;
    int N = sizeof(arr) / sizeof(arr[0]);
    if (isOddSumPossible(arr, N, K, 0)) {
        cout << "Possible";
    } else {
        cout << "Not Possible";
    }
    return 0;
}


Java




import java.util.Arrays;
 
public class GFG {
    // Function to check if it is possible to get an odd sum with exactly 'k' elements
    static boolean isOddSumPossible(int[] arr, int n, int k, int sum) {
        // If k is zero, check if the sum is odd
        if (k == 0) {
            return (sum % 2 != 0);
        }
        // If n is zero or k is negative, odd sum is not possible
        if (n == 0 || k < 0) {
            return false;
        }
        // Recur by including or excluding the current element
        return isOddSumPossible(arr, n - 1, k - 1, sum + arr[n - 1]) ||
               isOddSumPossible(arr, n - 1, k, sum);
    }
 
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 8};
        int K = 5;
        int N = arr.length;
         
        // Check if it is possible to get an odd sum with exactly 'K' elements
        if (isOddSumPossible(arr, N, K, 0)) {
            System.out.println("Possible");
        } else {
            System.out.println("Not Possible");
        }
    }
}


Python




def is_odd_sum_possible_optimized(arr, n, k, memo):
    if k == 0:
        return sum(arr) % 2 != 0
    if n == 0 or k < 0:
        return False
 
    if memo[n][k] != -1:
        return memo[n][k]
 
    include = is_odd_sum_possible_optimized(arr, n - 1, k - 1, memo)
    exclude = is_odd_sum_possible_optimized(arr, n - 1, k, memo)
 
    memo[n][k] = include or exclude
 
    return memo[n][k]
 
def main():
    arr = [1, 2, 3, 4, 5, 8]
    K = 5
    N = len(arr)
     
    # Initialize memoization table with -1
    memo = [[-1] * (K + 1) for _ in range(N + 1)]
 
    if is_odd_sum_possible_optimized(arr, N, K, memo):
        print("Possible")
    else:
        print("Not Possible")
 
if __name__ == "__main__":
    main()


C#




using System;
 
public class GFG
{
    public static bool IsOddSumPossible(int[] arr, int n, int k, int sum)
    {
        // If k is zero, check if the sum is odd
        if (k == 0)
        {
            return (sum % 2 != 0);
        }
        // If n is zero or k is negative, odd sum is not possible
        if (n == 0 || k < 0)
        {
            return false;
        }
        // Recur by including or excluding the current element
        return IsOddSumPossible(arr, n - 1, k - 1, sum + arr[n - 1]) ||
               IsOddSumPossible(arr, n - 1, k, sum);
    }
 
    public static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5, 8 };
        int K = 5;
        int N = arr.Length;
        if (IsOddSumPossible(arr, N, K, 0))
        {
            Console.WriteLine("Possible");
        }
        else
        {
            Console.WriteLine("Not Possible");
        }
    }
}


Javascript




function isOddSumPossible(arr, n, k, sum) {
    // If k is zero, check if the sum is odd
    if (k === 0) {
        return sum % 2 !== 0;
    }
    // If n is zero or k is negative, odd sum is not possible
    if (n === 0 || k < 0) {
        return false;
    }
    // Recur by including or excluding the current element
    return isOddSumPossible(arr, n - 1, k - 1, sum + arr[n - 1]) ||
        isOddSumPossible(arr, n - 1, k, sum);
}
 
const arr = [1, 2, 3, 4, 5, 8];
const K = 5;
const N = arr.length;
 
if (isOddSumPossible(arr, N, K, 0)) {
    console.log("Possible");
} else {
    console.log("Not Possible");
}


Output

Possible





Time complexity: O(2^n), as there are 2^n possible subsets of the input array.
Auxiliary Space: O(n),as the recursion stack can have at most n function calls.



Last Updated : 14 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads