Last element remaining after repeated removal of Array elements at perfect square indices | Java implementation of the above approach ; Function to find last remaining index after repeated removal of perfect square indices ; Initialize the ans variable as N ; Iterate a while loop and discard the possible values ; Total discarded values ; Check if this forms a perfect square ; Decrease answer by 1 ; Subtract the value from the current value of N ; Return the value remained ; Function to find last remaining element after repeated removal of array element at perfect square indices ; Find the remaining index ; Print the element at that index as the result ; Driver Code ; Given input
import java . util . * ; import java . lang . * ; import java . lang . Math ; class GFG { static int findRemainingIndex ( int N ) { int ans = N ; while ( N > 1 ) { int discard = ( int ) ( Math . sqrt ( N ) ) ; if ( discard * discard == N ) { ans -- ; } N -= discard ; } return ans ; } static void findRemainingElement ( int arr [ ] , int N ) { int remainingIndex = findRemainingIndex ( N ) ; System . out . print ( arr [ remainingIndex - 1 ] ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , 4 , 2 , 4 , - 3 , 1 , 1 } ; int N = 9 ; findRemainingElement ( arr , N ) ; } }