Maximum index a pointer can reach in N steps by avoiding a given index B | C ++ program for the above approach ; Function to find the maximum index reachable ; Store the answer ; Store the maximum index possible i . e , N * ( N - 1 ) ; Add bthe previous elements ; Run a loop ; Binary Search ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxIndex ( int N , int B ) { int maximumIndexReached = 0 ; vector < int > Ans ; for ( int i = 1 ; i <= N ; i ++ ) { maximumIndexReached += i ; Ans . push_back ( i ) ; } reverse ( Ans . begin ( ) , Ans . end ( ) ) ; for ( int i = 1 ; i < ( int ) Ans . size ( ) ; i ++ ) { Ans [ i ] += Ans [ i - 1 ] ; } while ( maximumIndexReached ) { auto it = lower_bound ( Ans . begin ( ) , Ans . end ( ) , maximumIndexReached - B ) ; if ( it == Ans . end ( ) ) { break ; } if ( * it == maximumIndexReached - B ) { maximumIndexReached -- ; } else { break ; } } return maximumIndexReached ; } int main ( ) { int N = 3 , B = 2 ; cout << maxIndex ( N , B ) ; return 0 ; }