Reduce given array by replacing subarrays with values less than K with their sum | C ++ program for the above approach ; Function to replace all the subarray having values < K with their sum ; Stores the sum of subarray having elements less than K ; Stores the updated array ; Traverse the array ; Update the sum ; Otherwise , update the vector ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void updateArray ( vector < int > & arr , int K ) { int sum = 0 ; vector < int > res ; for ( int i = 0 ; i < ( int ) arr . size ( ) ; i ++ ) { if ( arr [ i ] < K ) { sum += arr [ i ] ; } else { if ( sum != 0 ) { res . push_back ( sum ) ; } sum = 0 ; res . push_back ( arr [ i ] ) ; } } if ( sum != 0 ) res . push_back ( sum ) ; for ( auto & it : res ) cout << it << ' ▁ ' ; } int main ( ) { vector < int > arr = { 200 , 6 , 36 , 612 , 121 , 66 , 63 , 39 , 668 , 108 } ; int K = 100 ; updateArray ( arr , K ) ; return 0 ; }