Maximum index a pointer can reach in N steps by avoiding a given index B | JavaScript Program to implement 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
function lowerBound ( Ans , target ) { const targetRange = [ - 1 , - 1 ] const leftIdx = extremeInsertionIndex ( Ans , target , true ) if ( leftIdx === Ans . length Ans [ leftIdx ] != target ) return targetRange targetRange [ 0 ] = leftIdx targetRange [ 1 ] = extremeInsertionIndex ( Ans , target , false ) - 1 return targetRange function extremeInsertionIndex ( Ans , target , left ) { let lo = 0 , hi = Ans . length while ( lo < hi ) { const mid = lo + Math . floor ( ( hi - lo ) / 2 ) if ( Ans [ mid ] > target || ( left && target === Ans [ mid ] ) ) hi = mid else lo = mid + 1 } return lo } } function maxIndex ( N , B ) { let maximumIndexReached = 0 ; let Ans = [ ] ; for ( let i = 1 ; i <= N ; i ++ ) { maximumIndexReached += i ; Ans . push ( i ) ; } Ans . reverse ( ) ; for ( let i = 1 ; i < Ans . length ; i ++ ) { Ans [ i ] += Ans [ i - 1 ] ; } while ( maximumIndexReached ) { let it = lowerBound ( Ans , maximumIndexReached - B ) ; if ( it == - 1 ) { break ; } if ( it == maximumIndexReached - B ) { maximumIndexReached -- ; } else { break ; } } return maximumIndexReached ; } let N = 3 , B = 2 ; document . write ( maxIndex ( N , B ) ) ;