EDU Two Pointers Method step 3

Revision en4, by SeniorBOTx, 2022-05-16 20:34:23

In step 3 , question number 1 : I write two codes very similar to each , As i am a newbie can you help me out to find what is difference in two code. I got ac in one submission and wrong answer in other.

Also if you don not know what difference between two code, give this blog a upvote so many people can see it.

AC : [submission:157416384] WA : [submission:157415655]

problem : [problem:307094A]

`

AC : ~~~~~

void solve() { int n, p; cin >> n >> p; int sum{}, ans = 0 , res{}, index{}, prefix{};

vector<int> v(2 * n);
rep(i, 0, n) {
    cin >> v[i];
    v[i + n] = v[i];
    sum += v[i];
}

if (sum < p) {
    res = p / sum * n;
    p %= sum;
}
if (p != 0) {
    ans = INT_MAX;
    for (int r = 0, l = 0; r < 2 * n ; r++ ) {
       prefix += v[r];
       while (l < n and prefix >= p) {
         if (ans > r - l + 1) {
          ans = r - l + 1;
          index = l ;
         }
         prefix -= v[l];
         l++;
       }
    }
}
cout << index + 1 << " " << ans  + res << endl;

} ~~~~~ `

WA : ~~~~~

void solve() { int n, p; cin >> n >> p; int sum{}, ans = LLONG_MAX , res{}, index{}, prefix{};

vector<int> v(2 * n);
rep(i, 0, n) {
    cin >> v[i];
    v[i + n] = v[i];
    sum += v[i];
}

if (sum < p) {
    res = p / sum * n;
    p %= sum;
}

for (int r = 0, l = 0; r < 2 * n ; r++ ) {
    prefix += v[r];
    while (l < n and prefix >= p) {
       if (ans > r - l + 1) {
         ans = r - l + 1;
         index = l + 1;
       }
       prefix -= v[l]; l++;
    }
}

cout << index << " " << ans  + res << endl;

}

~~~~~

[meanwhile this is my first time here]

Tags two pointers, array, education

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en7 English SeniorBOTx 2022-05-16 20:37:42 8
en6 English SeniorBOTx 2022-05-16 20:37:15 54
en5 English SeniorBOTx 2022-05-16 20:35:27 14
en4 English SeniorBOTx 2022-05-16 20:34:23 12
en3 English SeniorBOTx 2022-05-16 20:33:00 8
en2 English SeniorBOTx 2022-05-16 20:32:17 1287
en1 English SeniorBOTx 2022-05-16 20:30:59 2901 Initial revision (published)