< Back to forum

my code is giving right output but in codechef it is not giving right ans to all test cases ..LINK TO QUESTN (ZCO14002)... https://www.codechef.com/ZCOPRAC/problems/ZCO14002

#include<bits/stdc++.h>


#define ll long long int
#define mp make_pair
#define pb push_back

using namespace std;

ll a[200000];



int main()
{
ll n,i,s,z,x,j,pos;
cin>>n;


for(i=0;i<200000;i++)
    {
      a[i]=100000;
    }

s=0;



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





 if((a[0]<=a[1])&&(a[0]<=a[2]))
 {
     i=0;
 }

 else if((a[1]<=a[2])&&(a[1]<=a[0]))
 {
    i=1;
 }

 else
    i=2;


//cout<<i<<" ";
s=s+a[i];


for(;i<n;)
{

 if((a[i+1]<=a[i+2])&&(a[i+1]<=a[i+3]))
 {
     pos=i+1;
 }

 else if((a[i+2]<=a[i+1])&&(a[i+2]<=a[i+3]))
 {
    pos=i+2;
 }

 else
    pos=i+3;

 //cout<<a[pos]<<" "<<pos<<" ";


  i=pos;

 s=s+a[pos];

 if(i>=(n-2))
    break;


}


cout<<s;


return 0;
}

 

Asked by: Manish_Kumar_Savita on April 7, 2019, 6:34 p.m. Last updated on April 7, 2019, 6:34 p.m.


Enter your answer details below:


Enter your comment details below:




2 Answer(s)

avatar

You have assumed that selection of minimum among the first three numbers will always give you optimal result. But it is not always correct.

For Test case:

5
1 2 3 4 1

Your code's output is 4, but the correct answer will be 3.

Ruchi_Singh last updated on April 7, 2019, 6:34 p.m. 0    Reply    Upvote   

avatar

the intuition behind your code is not correct. so, try to fix it.

note1 :) you should improve your skills regarding how to write code.

note2 :) you should explain the working of your program or how you think to solve the problem instead of just posting the code.

note 3:) always try some random test cases and corner cases before submitting the solution and don't just stick with test cases.

rishup132 last updated on April 7, 2019, 6:34 p.m. 0    Reply    Upvote   

Instruction to write good question
  1. 1. Write a title that summarizes the specific problem
  2. 2. Pretend you're talking to a busy colleague
  3. 3. Spelling, grammar and punctuation are important!

Bad: C# Math Confusion
Good: Why does using float instead of int give me different results when all of my inputs are integers?
Bad: [php] session doubt
Good: How can I redirect users to different pages based on session data in PHP?
Bad: android if else problems
Good: Why does str == "value" evaluate to false when str is set to "value"?

Refer to Stack Overflow guide on asking a good question.