Find the last positive element remaining after repeated subtractions of smallest positive element from all Array elements | 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
function lastPositiveElement ( arr ) { let N = arr . length ; if ( N == 1 ) return arr [ 0 ] ; let greatest = - 1 , secondGreatest = - 1 ; for ( let x of arr ) { if ( x >= greatest ) { secondGreatest = greatest ; greatest = x ; } else if ( x >= secondGreatest ) { secondGreatest = x ; } } return greatest - secondGreatest ; } let arr = [ 3 , 5 , 4 , 7 ] ; document . write ( lastPositiveElement ( arr ) ) ;