Minimize the sum of differences of consecutive elements after removing exactly K elements | C ++ implementation of the above approach . ; function to find minimum sum ; variable to store final answer and initialising it with the values when 0 elements is removed from the left and K from the right . ; loop to simulate removal of elements ; removing i elements from the left and and K - i elements from the right and updating the answer correspondingly ; returning final answer ; driver function ; input values ; callin the required function ;
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int * arr , int n , int k ) { int ans = arr [ n - k - 1 ] - arr [ 0 ] ; for ( int i = 1 ; i <= k ; i ++ ) { ans = min ( arr [ n - 1 - ( k - i ) ] - arr [ i ] , ans ) ; } return ans ; } int32_t main ( ) { int arr [ ] = { 1 , 2 , 100 , 120 , 140 } ; int k = 2 ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findSum ( arr , n , k ) ; }