Find the last positive element remaining after repeated subtractions of smallest positive element from all Array elements | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lastPositiveElement ( vector < int > arr ) { int N = arr . size ( ) ; 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 ; } int main ( ) { vector < int > arr = { 3 , 5 , 4 , 7 } ; cout << lastPositiveElement ( arr ) ; return 0 ; }