mocha_nirvana
mocha_nirvana

Reputation: 39

What's the difference between start=i,end=j; and start=i; end=j;

The question was "Max Continuous Series of 1s"

You are given an array of 1s and 0s. And you are given an integer M, which signifies number of flips allowed.

Find the position of zeros which when flipped will produce maximum continuous series of 1s.

I used sliding window approach to solve the answer, but there is something I noticed that if I write start=i;end=j; its wrong, but start=i,end=j; is right.

What's the difference between the execution of them?

vector<int> Solution::maxone(vector<int> &A, int B) {
    int n=A.size();
    int start=0,end=0,count=0,i,j;
    
    for(i=0,j=0;j<n;){
        if(B>=0 && !A[j++])
       
        B--;
        
        if(B<0 && !A[i++])
        
        B++;
        
        if(end-start<j-i)
        start=i,end=j;    // Here I get wrong ans if I write start=i;end=j;
    }
    
    vector<int> v;
    while(start<end)
    v.push_back(start++);
    
    return v;
    
}

Upvotes: 0

Views: 202

Answers (3)

Pete Becker
Pete Becker

Reputation: 76285

start = i, end = j; is a single statement. start = i; end = j; is two statements. An if controls the next statement. So:

if (false)
    start = i, end = j;

doesn’t modify start or end.

if (false)
    start = i; end = j;

modifies end because end = j is the second statement after the if, so the if does not affect it.

if (false) {
    start = i; end = j;
}

doesn’t modify start or end because both assignments are inside the compound statement delimited by the curly braces. The compound statement is the single statement that the if controls.

Upvotes: 2

HandsomeCoder
HandsomeCoder

Reputation: 756

Firstly, the problem is simple if you are not using curly brackets {} due without curly brackets so only one statement (not line) is considered under if as true statement so as soon as you put ; it will complete the one statement.

if()
    <true statement>;

if(){
   <true statement>;
   <true statement>;
}

Secondly, if you format your code properly then you will easily able to get the bug.

Finally, when you keep , instead of ; then it will be considered as single statement

Upvotes: 1

slsy
slsy

Reputation: 1304

In case of start=i;end=j; you get

if(end-start<j-i)
  start=i;
end = j;

because ; make end=j; an another statement

start=i,end=j; is a one statement, because comma is a Comma operator

Solution: use if() {}

Upvotes: 7

Related Questions