greedy - The two pointer algorithm -


i'm trying understand 2 pointer algorithm approach, i've been reading this article

so here question. suppose have array of n elements. , want find largest contiguous sequence of elements in array sum less or equal m. have return value sequence of elements sums to.

so suppose have array of elements [2, 1, 3, 4, 5] , our m 12. return 12 because 3, 4, , 5 sum 12. here approach article

  • we introduce 2 pointers l, r denoting startindex , endindex of our contiguous subarray, both of them @ tip of array.
  • we start extending our right pointer r provided sum[l,r] <= m once, reach @ such stage, don't have option move left pointer , start decreasing sum until arrive @ situation can extend our right pointer again.
  • as , when reach point, need shift left pointer, keep updating our maximum sum have achieved far.

and here c++ code.

#include <bits/stdc++.h> #define lli long long #define max 1000005  using namespace std;  lli a[max];  int main() {     int n;     lli sum = 0;          cin >> n;      ( int = 0; < n; i++ ) cin >> a[i];      int l = 0, r = 0;     lli ans = 0;      while ( l < n ) {        while ( r < n && sum + a[r] <= m ) {            sum += a[r];            r++;        }        ans = max(ans, sum);        sum -= a[l];        l++;     }      cout << ans << endl;     return 0; } 

but don't understand why approach works. not considering possible contiguous sub sequences. sum exceeded, take note of our current sub sequence length, compare see if it's larger previous one, , increment l , repeat process.

i don't see how yields correct result.

the approach works because each r pointer, current l represents furthest 1 left such sum still below threshold.

therefore not necessary other sequences end @ r pointer.

however, approach not valid if negative numbers allowed. in case, longer l - r sequence not mean sum increase.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -