Check if sum of exactly K elements of the Array can be odd or not
Last Updated :
14 Oct, 2023
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>
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");
}
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.
Similar Reads
Check if even and odd count of elements can be made equal in Array
Given an array Arr[] of N integers and an integer K, the task is to find if it is possible to make the count of even and odd elements equal by performing the following operations at most K times: Choose any index i such that Arr[i] is even and divide it by 2.Choose any index i such that Arr[i] is od
9 min read
Check if sum of the given array can be reduced to 0 by reducing array elements by K
Given an array arr[] consisting of N integers and an integer K, the task is to check if the sum of the array can be reduced to 0 by subtracting array elements by K any number of times. Examples: Input: arr[ ]= {-3, 2, -1, 5, 1}, K=2Output: "Yes"Explanation: Sum of the array is 4. Therefore, decreasi
4 min read
Check if a given array can be divided into pairs with even sum
Given an array arr[] consisting of N integers, the task is to check if it is possible to divide the entire array into pairs such that the sum of each pair is even. If it is possible, print "Yes". Otherwise, print "No". Examples: Input: arr[] = {3, 2, 1, 4, 7, 5, }Output: YesExplanation:The given arr
6 min read
Check if Array can be sorted by swapping adjacent elements having odd sum
Given an array arr[], the task is to check if the array can be sorted using the given operation any number of times. In one operation, you can swap any two adjacent elements if their sum is odd. Examples: Input: arr[] = [1, 6, 31, 14]Output: YesExplanation: Swap 31 and 14 (31 + 14 = 45 which is odd)
7 min read
Check if given integer is whole or partial sum of given Array elements
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 = 6Output: TrueExplanation: 1 + 2 + 3 = 6 Input: A[] = {15, 12, 13, 10},
6 min read
Check if the XOR of an array of integers is Even or Odd
Given an array arr containing integers of size N, the task is to check if the XOR of this array is even or odd Examples: Input: arr[] = { 2, 4, 7} Output: Odd Explanation: XOR of array = 2 ^ 4 ^ 7 = 1, which is odd Input: arr[] = { 3, 9, 12, 13, 15 } Output: Even Naive Solution: First find the XOR o
5 min read
Check if an array of 1s and 2s can be divided into 2 parts with equal sum
Given an array containing N elements, each element is either 1 or 2. The task is to find out whether the array can be divided into 2 parts such that the sum of elements in both parts is equal.Examples:Input : N = 3, arr[] = {1, 1, 2}Output : YESInput : N = 4, arr[] = {1, 2, 2, }Output : NOThe idea i
13 min read
Check if all elements of a Circular Array can be made equal by increments of adjacent pairs
Given a circular array arr[] of size N, the task is to check if it is possible to make all array elements of the circular array equal by increasing pairs of adjacent elements by 1. Examples: Input: N = 4, arr[] = {2, 1, 3, 4} Output:YesExplanation:Step 1: {2, 1, 3, 4} -> {3, 2, 3, 4}Step 2: {3, 2
5 min read
Check if array sum can be made K by three operations on it
Given an array A of N integers and a positive integer K. Only three operations can be performed on this array: Replace an integer with the negative value of the integer, Add index number (1-based indexing) of the element to the element itself and Subtract index number of the element from the element
9 min read
Find if sum of elements of given Array is less than or equal to K
Given an array arr[] of size N and an integer K, the task is to find whether the sum of elements of the array is less than or equal to K or not. Examples: Input: arr[] = {1, 2, 8}, K = 5Output: falseExplanation: Sum of the array is 11, which is greater than 5 Input: arr[] = {2}, K = 5Output: true Ap
3 min read