JULY LUNCHTIME 2021

https://www.codechef.com/problems/REDALERT

for the redalert problem, if i write my code as follows:

#include
using namespace std;

int main() {
int t;
cin>>t;

while(t--){
    int n,d,h,x,flag=0;
    cin>>n>>d>>h;
    int sum=0,a[n];

    for(int i=0; i<n; i++){
        cin>>a[i];
    }

    for(int i=0; i<n; i++){
       
       if(a[i]>0){
           sum+=a[i];
       }else if(a[i]==0 && sum>d){
           sum=sum-d;
       }else if(a[i]==0 && sum<=d){
           sum=0;
       }       

       if(sum>h){
           flag=1;
           cout<<"YES"<<endl;
           break;}
  
    }

    if(flag==0){
        cout<<"NO"<<endl;
    }
}

return 0;

}

SecondCode::

#include
using namespace std;

int main() {
int t;
cin>>t;

while(t--){

    int n,d,h,x,flag=0;
    cin>>n>>d>>h;
    int sum=0,a[n];
    
    for(int i=0; i<n; i++){

       cin>>a[i];

       if(a[i]>0){
          sum+=a[i];
       }else if(a[i]==0 && sum>d){
           sum=sum-d;
       }else if(a[i]==0 && sum<=d){
          sum=0;
       }
       
       if(sum>h){
           flag=1;
           cout<<"YES"<<endl;
          break;    }

    }

    if(flag==0){
        cout<<"NO"<<endl;
    }

}

return 0;

}

briefly my first code is written by taking inputs in a seperate loop and for checking conditions I used another loop, it shows as correct answer after submission but if I use only a single loop then I am getting as wrong answer after submission… can anyone please just clarify me why is this happening… In what way and how they both differ !!

In the second code, you are breaking from the loop if the sum is > h. If you do this while reading input, the code won’t read the entire input.
For example, let’s assume the input is given as the following:
2
5 2
1 2 3 4 5
1 2
1
(First test case, with N = 5, h = 2)
when you read 2, the sum becomes 3 and you break from the loop. So, the code starts reading input from 3 onwards (meaning that 3 becomes the N of the second test case, 4 becomes the h, and so on.

So just remove the two lines in the if statement and place them after the loop. It will work fine.

2 Likes

Got it, Thank you :slight_smile:

1 Like