Find the last positive element remaining after repeated subtractions of smallest positive element from all Array elements | JAVA program for the above approach ; Function to calculate last positive element of the array ; Return the first element if N = 1 ; Stores the greatest and the second greatest element ; Traverse the array A [ ] ; If current element is greater than the greatest element ; If current element is greater than second greatest element ; Return the final answer ; Driver Code
import java . util . * ; class GFG { static int lastPositiveElement ( int [ ] arr ) { int N = arr . length ; if ( N == 1 ) return arr [ 0 ] ; int greatest = - 1 , secondGreatest = - 1 ; for ( int x : arr ) { if ( x >= greatest ) { secondGreatest = greatest ; greatest = x ; } else if ( x >= secondGreatest ) { secondGreatest = x ; } } return greatest - secondGreatest ; } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 5 , 4 , 7 } ; System . out . print ( lastPositiveElement ( arr ) ) ; } }