Maximum index a pointer can reach in N steps by avoiding a given index B | Python 3 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
from bisect import bisect_left NEW_LINE def maxIndex ( N , B ) : NEW_LINE INDENT maximumIndexReached = 0 NEW_LINE Ans = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT maximumIndexReached += i NEW_LINE Ans . append ( i ) NEW_LINE DEDENT Ans . reverse ( ) NEW_LINE for i in range ( len ( Ans ) ) : NEW_LINE INDENT Ans [ i ] += Ans [ i - 1 ] NEW_LINE DEDENT while ( maximumIndexReached ) : NEW_LINE INDENT it = bisect_left ( Ans , maximumIndexReached - B ) NEW_LINE if ( it not in Ans ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( it == maximumIndexReached - B ) : NEW_LINE INDENT maximumIndexReached -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return maximumIndexReached NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE B = 2 NEW_LINE print ( maxIndex ( N , B ) ) NEW_LINE DEDENT