Maximum Length Even Subarray Problem Code: MXEVNSUB Codechef Solution

 



Maximum Length Even Subarray Problem Code: MXEVNSUB
Submit

Read problem statements in MandarinBengaliRussian, and Vietnamese as well.

You are given an integer N. Consider the sequence containing the integers 1,2,,N in increasing order (each exactly once). Find the maximum length of its contiguous subsequence with an even sum.

Input Format

  • The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
  • The first and only line of each test case contains a single integer N.

Output Format

For each test case, print a single line containing one integer --- the maximum length of a contiguous subsequence with even sum.

Constraints

  • 1T104
  • 2N104

Subtasks

Subtask #1 (100 points): original constraints

Sample Input 1 

3
3
4
5

Sample Output 1 

3
4
4

Explanation

Example case 1: The optimal choice is to choose the entire sequence, since the sum of all its elements is 1+2+3=6, which is even.

Example case 3: One of the optimal choices is to choose the subsequence [1,2,3,4], which has an even sum.


















































Solution in C


#include<stdio.h>

int main()

{

    int n;

    scanf("%d",&n);

    for(int k=0;k<n;k++)

    {

        int p;

        scanf("%d",&p);

        int sum=0;

        for(int k=1;k<=p;k++)

        {

            sum=sum+k;

        }

        if(sum%2==0)

        {

            printf("%d",p);

        }

        else{

            printf("%d",p-1);

        }

        printf("\n");

    }

}






Solution in C++



#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
if((n%2)==1&&((n+2)/2)%2==1)
{
cout<<n-1<<"\n";
}
else if((n%2)==1&&((n+1)/2)%2==0)
{
cout<<n<<"\n";
}
else if((n%2)==0&&(n/2)%2==0)
{
cout<<n<<"\n";
}
else{
cout<<n-1<<"\n";
}
}
}

Comments