Maximum index a pointer can reach in N steps by avoiding a given index B | Set 2 | C ++ program for the above approach ; Function to find the maximum index the pointer can reach ; Initialize two pointers ; Stores number of steps ; Stores sum of first N natural numbers ; Increment i with j ; Increment j with 1 ; Increment count ; If i points to B ; Break ; Print the pointer index ; Driver Code ; Given value of N & B ; Function call to find maximum index the pointer can reach
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumIndex ( int N , int B ) { int i = 0 , j = 1 ; int cnt = 0 ; int sum = N * ( N + 1 ) / 2 ; bool flag = false ; while ( cnt < N ) { i += j ; j ++ ; cnt ++ ; if ( i == B ) { flag = true ; break ; } } if ( ! flag ) { cout << sum ; } else cout << sum - 1 ; } int main ( ) { int N = 4 , B = 6 ; maximumIndex ( N , B ) ; return 0 ; }