PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Author: Daanish Mahajan
Tester: Anay Karnik
Editorialist: Mohan Abhyas
DIFFICULTY:
Cakewalk
PREREQUISITES:
None
PROBLEM:
You are given an integer N. Consider the sequence containing the integers 1, 2, \ldots, N in increasing order (each exactly once). Find the maximum length of its contiguous subsequence with an even sum.
EXPLANATION:
\sum_{k=1}^{k=n} k = n*(n+1)/2
Take whole sequence if above sum is even else leave out 1 to make sum even
TIME COMPLEXITY:
\mathcal{O}(1) per testcase.
SOLUTIONS:
[details = âEditorialâs Solutionâ]
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define forn(i,e) for(ll i = 0; i < e; i++)
void solve()
{
ll n;
cin>>n;
ll sum = (n*(n+1))/2;
if(sum%2)
{
cout<<n-1<<endl;
}
else
{
cout<<n<<endl;
}
}
int main()
{
ll t=1;
cin >> t;
forn(i,t) {
solve();
}
return 0;
}
in case of 10 it will be , 2+3+4+5+6+7+8+9+10 = 54
1 Like
then answer will be 1, {2}.
whatâs wrong in this code??
#include
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t!=0)
{
int n;
cin>>n;
int count=n;
int sum;
for(int i=1;i<=n;i++)
{
sum+=i;
}
if(sum%2!=0)
{
sum=sum-(n);
countâ;
if(sum%2!=0)
{
countâ;
cout<<count<<endl;
}
else
{
cout<<count<<endl;
}
}
else
{
cout<<count<<endl;
}
tâ;
}
return 0;
}
Can someone help in this?

This shows wrong answerâŚ
This solution would be the ideal solution in my opinion
t=int(input())
while(t):
n=int(input())
if(((n*(n+1))/2)%2==0):
print(n)
else:
print(n-1)
t-=1
You should check the sum of entire series. In that way if sum is odd just one can be removed to make it largest even sum subsequence
What youâre doing fails for numbers like 10. (Ans should be 9 but your code gives 8)!
Hope this helps even a little bit!
1 Like
At 10 code provides 9 as outputđ
Brother I could see that you didnât intialize the sum variable to 0 before using it. So when you write sum+=i you are adding it to the garbage value. Sum has garbage value(unpredictible value) in it.
Replace int sum with int sum=0;
Also you are adding extra couts i mean remove all those else statements and replace them with just single cout<<count<<endl; as this will do the job.
Also this logic is not what the question asked. I did the same logic untill i saw the editorial loll.
Happy to hear back from you brother love from India
from sys import stdin
for _ in range(int(stdin.readline())):
n = int(stdin.readline())
print (n if (n+1)//2%2==0 else n-1)
To save a multiply operation only (n+1)//2 needs to be checked for parity. Yes, I know its miniscule, but in systems running 100 billion operations every second it really helps.
The editorial Solution should fail if N=14.
Correct me if I am wrong?