📌  相关文章
📜  精确删除K个元素后,最大化连续元素的差之和

📅  最后修改于: 2021-04-27 05:44:17             🧑  作者: Mango

给定长度为N且整数KK 的排序数组arr [] ,任务是从数组中准确删除K个元素,以使该数组连续元素之差的总和最大。
例子:

方法:有两种情况:

  1. 如果K 则答案将是arr [N – 1] – arr [0] 。这是因为可以删除数组的N – 2个内部元素中的任何K个元素,而不会影响最大差异之和。例如,如果必须从1、2、3和4中删除任何单个元素,那么无论是删除2还是删除3,最终的差总和都将保持不变,即((3-1 – 1)+(4 – 3))= 3,等于((2-1)+(4-2))= 3。
  2. 如果K = N – 1,则答案将为0,因为仅剩下一个元素,即最小和最大。因此,答案是0

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the maximized sum
int findSum(int* arr, int n, int k)
{
 
    // Remove any k internal elements
    if (k <= n - 2)
        return (arr[n - 1] - arr[0]);
 
    return 0;
}
 
// Driver code
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
// Java implementation of the approach
class GFG
{
     
    // Function to return the maximized sum
    static int findSum(int []arr, int n, int k)
    {
     
        // Remove any k internal elements
        if (k <= n - 2)
            return (arr[n - 1] - arr[0]);
     
        return 0;
    }
     
    // Driver code
    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));
    }
}
 
// This code is contributed by AnkitRai01


Python3
# Python3 implementation of the approach
 
# Function to return the maximized sum
def findSum(arr, n, k) :
 
    # Remove any k internal elements
    if (k <= n - 2) :
        return (arr[n - 1] - arr[0]);
         
    return 0;
     
# Driver code
if __name__ == "__main__" :
 
    arr = [ 1, 2, 3, 4 ];
    n = len(arr);
    k = 1;
 
    print(findSum(arr, n, k));
     
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to return the maximized sum
    static int findSum(int []arr,
                       int n, int k)
    {
     
        // Remove any k internal elements
        if (k <= n - 2)
            return (arr[n - 1] - arr[0]);
     
        return 0;
    }
     
    // Driver code
    public static void Main ()
    {
        int []arr = { 1, 2, 3, 4 };
        int n = arr.Length;
        int k = 1;
     
        Console.WriteLine(findSum(arr, n, k));
    }
}
 
// This code is contributed by AnkitRai01


输出:
3

时间复杂度: O(1)

辅助空间: O(1)