- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- Related Questions & Answers
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Program to find length of longest sublist whose sum is 0 in Python
- C++ program to find string with palindrome substring whose length is at most k
- Program to find length of longest substring with even vowel counts in Python
- Program to find length of longest path with even sum in Python
- Program to find length of longest common substring in C++
- Program to find length of longest palindromic substring in Python
- C++ Program to find length of maximum non-decreasing subsegment
- C++ code to find palindrome string whose substring is S
- Program to find length of longest consecutively increasing substring in Python
- C++ Program to find length of substring song from main song
- Program to find product of few numbers whose sum is given in Python
- Program to find number of sublists whose sum is given target in python
- C++ program to find maximum possible median of elements whose sum is s
- C++ program to find range whose sum is same as n

Advertisements