Min steps to empty an Array by removing a pair each time with sum at most K | C ++ program for the above approach ; Function to count minimum steps ; Function to sort the array ; Run while loop ; Condition to check whether sum exceed the target or not ; Increment the step by 1 ; Return minimum steps ; Driver Code ; Given array arr [ ] ; Given target value ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinSteps ( int arr [ ] , int target , int n ) { sort ( arr , arr + n ) ; int minimumSteps = 0 ; int i = 0 , j = n - 1 ; while ( i <= j ) { if ( arr [ i ] + arr [ j ] <= target ) { i ++ ; j -- ; } else { j -- ; } minimumSteps ++ ; } return minimumSteps ; } int main ( ) { int arr [ ] = { 4 , 6 , 2 , 9 , 6 , 5 , 8 , 10 } ; int target = 11 ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countMinSteps ( arr , target , size ) ; return 0 ; }