Longest subsequence of even numbers in an Array
Last Updated :
25 May, 2021
Given an array arr[] containing N integers, the task is to print the length of the longest subsequence of even numbers in the array.
Examples:
Input: arr[] = {3, 4, 11, 2, 9, 21}
Output: 2
Explanation:
The longest subsequence containing even numbers is {4, 2}.
Hence, the answer is 2.
Input: arr[] = {6, 4, 10, 13, 9, 25}
Output: 3
The longest subsequence containing even numbers is {6, 4, 10}.
Hence, the answer is 3.
Approach: One observation that needs to be made from the array is that the longest subsequence containing only an even number will be the total count of all the even numbers. Therefore, the following steps are followed to compute the answer:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define N 100000
int longestEvenSubsequence( int arr[], int n)
{
int answer = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
answer++;
}
}
return answer;
}
int main()
{
int arr[] = { 3, 4, 11, 2, 9, 21 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << longestEvenSubsequence(arr, n)
<< endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static int longestEvenSubsequence( int arr[], int n)
{
int answer = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (arr[i] % 2 == 0 )
{
answer++;
}
}
return answer;
}
public static void main(String args[])
{
int []arr = { 3 , 4 , 11 , 2 , 9 , 21 };
int n = arr.length;
System.out.print(longestEvenSubsequence(arr, n));
}
}
|
Python3
N = 100000
def longestEvenSubsequence(arr, n):
answer = 0
for i in range (n):
if (arr[i] % 2 = = 0 ):
answer + = 1
return answer
if __name__ = = "__main__" :
arr = [ 3 , 4 , 11 , 2 , 9 , 21 ]
n = len (arr)
print (longestEvenSubsequence(arr, n))
|
C#
using System;
class GFG{
static int longestEvenSubsequence( int []arr, int n)
{
int answer = 0;
for ( int i = 0; i < n; i++)
{
if (arr[i] % 2 == 0)
{
answer++;
}
}
return answer;
}
public static void Main()
{
int []arr = { 3, 4, 11, 2, 9, 21 };
int n = arr.Length;
Console.WriteLine(longestEvenSubsequence(arr, n));
}
}
|
Javascript
<script>
let N = 100000;
function longestEvenSubsequence(arr, n) {
let answer = 0;
for (let i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
answer++;
}
}
return answer;
}
let arr = [3, 4, 11, 2, 9, 21];
let n = arr.length;
document.write(longestEvenSubsequence(arr, n) + "<br>" );
</script>
|
Time Complexity: O(N), where N is the length of the array.
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...