Maximize the sum of differences of consecutive elements after removing exactly K elements
Last Updated :
13 May, 2021
Given a sorted array arr[] of length N and an integer K such that K < N, the task is to remove exactly K elements from the array such that the sum of the differences of the consecutive elements of the array is maximized.
Examples:
Input: arr[] = {1, 2, 3, 4}, K = 1
Output: 3
Let’s consider all the possible cases:
a) Remove arr[0]: arr[] = {2, 3, 4}, ans = 2
b) Remove arr[1]: arr[] = {1, 3, 4}, ans = 3
c) Remove arr[2]: arr[] = {1, 2, 4}, ans = 3
d) Remove arr[3]: arr[] = {1, 2, 3}, ans = 2
3 is the maximum of all the answers.
Input: arr[] = {1, 2, 10}, K = 2
Output: 0
Approach: There are two cases:
- If K < N – 1 then the answer will be arr[N – 1] – arr[0]. This is because any K elements from the N – 2 internal elements of the array can be deleted without affecting the maximized sum of differences. For example, if any single element has to be removed from 1, 2, 3 and 4 then no matter whether 2 is removed or 3 is removed the final sum of difference will remain the same i.e. ((3 – 1) + (4 – 3)) = 3 which is equal to ((2 – 1) + (4 – 2)) = 3.
- If K = N – 1 then the answer will be 0 because only a single element remains that is both the minimum and the maximum. Thus, the answer is 0.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findSum( int * arr, int n, int k)
{
if (k <= n - 2)
return (arr[n - 1] - arr[0]);
return 0;
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int n = sizeof (arr) / sizeof ( int );
int k = 1;
cout << findSum(arr, n, k);
return 0;
}
|
Java
class GFG
{
static int findSum( int []arr, int n, int k)
{
if (k <= n - 2 )
return (arr[n - 1 ] - arr[ 0 ]);
return 0 ;
}
public static void main (String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 };
int n = arr.length;
int k = 1 ;
System.out.println(findSum(arr, n, k));
}
}
|
Python3
def findSum(arr, n, k) :
if (k < = n - 2 ) :
return (arr[n - 1 ] - arr[ 0 ]);
return 0 ;
if __name__ = = "__main__" :
arr = [ 1 , 2 , 3 , 4 ];
n = len (arr);
k = 1 ;
print (findSum(arr, n, k));
|
C#
using System;
class GFG
{
static int findSum( int []arr,
int n, int k)
{
if (k <= n - 2)
return (arr[n - 1] - arr[0]);
return 0;
}
public static void Main ()
{
int []arr = { 1, 2, 3, 4 };
int n = arr.Length;
int k = 1;
Console.WriteLine(findSum(arr, n, k));
}
}
|
Javascript
<script>
function findSum(arr, n, k)
{
if (k <= n - 2)
return (arr[n - 1] - arr[0]);
return 0;
}
var arr = [1, 2, 3, 4];
var n = arr.length;
var k = 1;
document.write( findSum(arr, n, k));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...