# C++ program to find length of non empty substring whose sum is even

Suppose we have an array A with n elements. We have to find the length of a non-empty subset of its elements such that their sum is even or return -1 when there is no such subset.

So, if the input is like A = [1, 3, 7], then the output will be 2, because sum of [1, 3] is 4.

## Steps

To solve this, we will follow these steps −

n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
if A[i] mod 2 is same as 0, then:
k := i + 1
if n is 1 AND k is 0, then:
return -1
otherwise when k is not equal to 0, then:
return 1
Otherwise
return 2

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(vector<int> A) {
long n = A.size(), k = 0;
for (long i = 0; i < n; i++) {
if (A[i] % 2 == 0) {
k = i + 1;
}
}
if (n == 1 & k == 0) {
return -1;
}
else if (k != 0) {
return 1;
} else {
return 2;
}
}
int main() {
vector<int> A = { 1, 3, 7 };
cout << solve(A) << endl;
}

## Input

{ 1, 3, 7 }

## Output

2