📌  相关文章
📜  最大化数组中K个角元素的总和

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

给定一个数组arr []一个整数K ,任务是通过仅获取边角元素来找到Array中K个元素的总和。

例子:

天真的方法:这个想法是使用递归。由于我们只能采用起始或终止索引值,因此需要初始化两个变量并精确地执行K步,并在所有可能的组合中返回最大和。递归方法由于具有重叠的子问题和最佳的子结构属性而具有指数复杂性。
下面是上述方法的实现:

C++
// C++ program to maximize the sum of K elements
// in the array by taking only corner elements
 
#include 
using namespace std;
 
// Function to return maximum sum
int maxSum(int arr[], int K,
           int start, int end,
           int max_sum)
{
    // Base case
    if (K == 0)
        return max_sum;
 
    // Pick the start index
    int max_sum_start = max_sum
                        + arr[start];
 
    // Pick the end index
    int max_sum_end = max_sum + arr[end];
 
    // Recursive function call
    int ans = max(
        maxSum(arr, K - 1, start + 1,
               end, max_sum_start),
        maxSum(arr, K - 1, start,
               end - 1, max_sum_end));
 
    // Return the final answer
    return ans;
}
 
// Function to find the maximized sum
void maximizeSum(int arr[], int K, int n)
{
    int max_sum = 0;
    int start = 0;
    int end = n - 1;
 
    cout << maxSum(arr, K, start,
                   end, max_sum);
}
 
// Driver code
int main()
{
    int arr[] = { 8, 4, 4, 8, 12, 3, 2, 9 };
    int K = 3;
    int n = sizeof(arr) / sizeof(arr[0]);
 
    maximizeSum(arr, K, n);
 
    return 0;
}


Java
// Java program to maximize the sum of K elements
// in the array by taking only corner elements
import java.util.*;
 
class GFG{
 
// Function to return maximum sum
static int maxSum(int arr[], int K,
                  int start, int end,
                  int max_sum)
{
    // Base case
    if (K == 0)
        return max_sum;
 
    // Pick the start index
    int max_sum_start = max_sum + arr[start];
 
    // Pick the end index
    int max_sum_end = max_sum + arr[end];
 
    // Recursive function call
    int ans = Math.max(maxSum(arr, K - 1, start + 1,
                              end, max_sum_start),
                       maxSum(arr, K - 1, start,
                              end - 1, max_sum_end));
 
    // Return the final answer
    return ans;
}
 
// Function to find the maximized sum
static void maximizeSum(int arr[], int K, int n)
{
    int max_sum = 0;
    int start = 0;
    int end = n - 1;
    System.out.print(maxSum(arr, K, start,
                            end, max_sum));
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 8, 4, 4, 8, 12, 3, 2, 9 };
    int K = 3;
    int n = arr.length;
    maximizeSum(arr, K, n);
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program to maximize the sum of K elements
# in the array by taking only corner elements
 
# Function to return maximum sum
def maxSum(arr, K, start, end, max_sum):
     
    # Base case
    if (K == 0):
        return max_sum
 
    # Pick the start index
    max_sum_start = max_sum + arr[start]
 
    # Pick the end index
    max_sum_end = max_sum + arr[end]
 
    # Recursive function call
    ans = max(maxSum(arr,  K - 1, start + 1,
                     end, max_sum_start),
          maxSum(arr, K - 1, start,
                     end - 1, max_sum_end))
 
    # Return the final answer
    return ans
 
# Function to find the maximized sum
def maximizeSum(arr, K, n):
    max_sum = 0
    start = 0
    end = n - 1
 
    print(maxSum(arr, K, start, end, max_sum))
 
# Driver code
if __name__ == '__main__':
     
    arr = [8, 4, 4, 8, 12, 3, 2, 9]
    K = 3
    n = len(arr)
 
    maximizeSum(arr, K, n)
 
# This code is contributed by Bhupendra_Singh


C#
// C# program to maximize the sum of K elements
// in the array by taking only corner elements
using System;
 
 class GFG{
 
// Function to return maximum sum
static int maxSum(int []arr, int K,
                  int start, int end,
                  int max_sum)
{
    // Base case
    if (K == 0)
        return max_sum;
 
    // Pick the start index
    int max_sum_start = max_sum + arr[start];
 
    // Pick the end index
    int max_sum_end = max_sum + arr[end];
 
    // Recursive function call
    int ans = Math.Max(maxSum(arr, K - 1, start + 1,
                              end, max_sum_start),
                       maxSum(arr, K - 1, start,
                              end - 1, max_sum_end));
 
    // Return the readonly answer
    return ans;
}
 
// Function to find the maximized sum
static void maximizeSum(int []arr, int K, int n)
{
    int max_sum = 0;
    int start = 0;
    int end = n - 1;
    Console.Write(maxSum(arr, K, start,
                         end, max_sum));
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 8, 4, 4, 8, 12, 3, 2, 9 };
    int K = 3;
    int n = arr.Length;
     
    maximizeSum(arr, K, n);
}
}
 
// This code is contributed by sapnasingh4991


C++
// C++ program to maximize the sum of K elements
// in the array by taking only corner elements
 
#include 
using namespace std;
 
// Function to return maximum sum
int maxPointCount(int arr[], int K, int size)
{
    // Initialse variables
    int curr_points = 0;
    int max_points = 0;
 
    // Iterate over first K elements of array
    // and update the value for curr_points
    for (int i = 0; i < K; i++)
        curr_points += arr[i];
 
    // Update value for max_points
    max_points = curr_points;
 
    // j points to the end of the array
    int j = size - 1;
 
    for (int i = K - 1; i >= 0; i--) {
 
        curr_points = curr_points
                      + arr[j] - arr[i];
        max_points = max(curr_points,
                         max_points);
        j--;
    }
 
    // Return the final result
    return max_points;
}
 
// Driver code
int main()
{
    int arr[] = { 8, 4, 4, 8, 12, 3, 2, 9 };
    int K = 3;
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << maxPointCount(arr, K, n);
 
    return 0;
}


Java
// Java program to maximize the sum
// of K elements in the array by
// taking only corner elements
import java.util.Scanner;
import java.util.Arrays;
 
class GFG{
 
// Function to return maximum sum
public static int maxPointCount(int arr[],
                                int K,
                                int size)
{
     
    // Initialse variables
    int curr_points = 0;
    int max_points = 0;
 
    // Iterate over first K elements
    // of array and update the value
    // for curr_points
    for(int i = 0; i < K; i++)
        curr_points += arr[i];
 
    // Update value for max_points
    max_points = curr_points;
 
    // j points to the end of the array
    int j = size - 1;
 
    for(int i = K - 1; i >= 0; i--)
    {
        curr_points = curr_points +
                      arr[j] - arr[i];
        max_points = Math.max(curr_points,
                              max_points);
        j--;
    }
 
    // Return the final result
    return max_points;
}
 
// Driver code
public static void main(String args[])
{
    int []arr = { 8, 4, 4, 8, 12, 3, 2, 9 };
    int K = 3;
    int n = arr.length;
 
    System.out.print( maxPointCount(arr, K, n));
}
}
 
// This code is contributed by SoumikMondal


Python3
# Python3 program to maximize the sum
# of K elements in the array by taking
# only corner elements
 
# Function to return maximum sum
def maxPointCount(arr, K, size):
 
    # Initialse variables
    curr_points = 0
    max_points = 0
 
    # Iterate over first K elements
    # of array and update the value
    # for curr_points
    for i in range(K):
        curr_points += arr[i]
 
    # Update value for max_points
    max_points = curr_points
 
    # j points to the end of the array
    j = size - 1
 
    for i in range(K - 1, -1, -1):
        curr_points = (curr_points +
                       arr[j] - arr[i])
        max_points = max(curr_points,
                         max_points)
        j -= 1
 
    # Return the final result
    return max_points
 
# Driver code
if __name__ == "__main__":
     
    arr = [ 8, 4, 4, 8, 12, 3, 2, 9 ]
    K = 3
    n = len(arr)
 
    print(maxPointCount(arr, K, n))
 
# This code is contributed by chitranayal


C#
// C# program to maximize the sum
// of K elements in the array by
// taking only corner elements
using System;
class GFG{
 
// Function to return maximum sum
public static int maxPointCount(int []arr,
                                int K,
                                int size)
{
     
    // Initialse variables
    int curr_points = 0;
    int max_points = 0;
 
    // Iterate over first K elements
    // of array and update the value
    // for curr_points
    for(int i = 0; i < K; i++)
        curr_points += arr[i];
 
    // Update value for max_points
    max_points = curr_points;
 
    // j points to the end of the array
    int j = size - 1;
 
    for(int i = K - 1; i >= 0; i--)
    {
        curr_points = curr_points +
                      arr[j] - arr[i];
        max_points = Math.Max(curr_points,
                              max_points);
        j--;
    }
 
    // Return the readonly result
    return max_points;
}
 
// Driver code
public static void Main(String []args)
{
    int []arr = { 8, 4, 4, 8, 12, 3, 2, 9 };
    int K = 3;
    int n = arr.Length;
 
    Console.Write( maxPointCount(arr, K, n));
}
}
 
// This code is contributed by sapnasingh4991


输出:
21

高效方法:为了更有效地解决问题,我们将实施“滑动窗口”概念。

  • 用0, curr_pointsmax_points初始化两个整数,分别代表当前点和最大点。
  • 现在,迭代K中的元素逐个从一开始,并形成大小K的窗口,也通过curr_points更新curr_points的值+ ARR [i]和与curr_points的值MAX_POINTS。
  • 之后,在每一步中,从数组的末尾取出一个元素,并从先前选择的窗口中删除最右边的元素,并从其开始时开始,窗口大小始终保持为K。相应地更新curr_points和max_points的值。最后,我们从数组末尾开始有K个元素,并且max_points包含必须返回的所需结果。

让我们看下面的图片,以更好地理解它:

下面是上述方法的实现:

C++

// C++ program to maximize the sum of K elements
// in the array by taking only corner elements
 
#include 
using namespace std;
 
// Function to return maximum sum
int maxPointCount(int arr[], int K, int size)
{
    // Initialse variables
    int curr_points = 0;
    int max_points = 0;
 
    // Iterate over first K elements of array
    // and update the value for curr_points
    for (int i = 0; i < K; i++)
        curr_points += arr[i];
 
    // Update value for max_points
    max_points = curr_points;
 
    // j points to the end of the array
    int j = size - 1;
 
    for (int i = K - 1; i >= 0; i--) {
 
        curr_points = curr_points
                      + arr[j] - arr[i];
        max_points = max(curr_points,
                         max_points);
        j--;
    }
 
    // Return the final result
    return max_points;
}
 
// Driver code
int main()
{
    int arr[] = { 8, 4, 4, 8, 12, 3, 2, 9 };
    int K = 3;
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << maxPointCount(arr, K, n);
 
    return 0;
}

Java

// Java program to maximize the sum
// of K elements in the array by
// taking only corner elements
import java.util.Scanner;
import java.util.Arrays;
 
class GFG{
 
// Function to return maximum sum
public static int maxPointCount(int arr[],
                                int K,
                                int size)
{
     
    // Initialse variables
    int curr_points = 0;
    int max_points = 0;
 
    // Iterate over first K elements
    // of array and update the value
    // for curr_points
    for(int i = 0; i < K; i++)
        curr_points += arr[i];
 
    // Update value for max_points
    max_points = curr_points;
 
    // j points to the end of the array
    int j = size - 1;
 
    for(int i = K - 1; i >= 0; i--)
    {
        curr_points = curr_points +
                      arr[j] - arr[i];
        max_points = Math.max(curr_points,
                              max_points);
        j--;
    }
 
    // Return the final result
    return max_points;
}
 
// Driver code
public static void main(String args[])
{
    int []arr = { 8, 4, 4, 8, 12, 3, 2, 9 };
    int K = 3;
    int n = arr.length;
 
    System.out.print( maxPointCount(arr, K, n));
}
}
 
// This code is contributed by SoumikMondal

Python3

# Python3 program to maximize the sum
# of K elements in the array by taking
# only corner elements
 
# Function to return maximum sum
def maxPointCount(arr, K, size):
 
    # Initialse variables
    curr_points = 0
    max_points = 0
 
    # Iterate over first K elements
    # of array and update the value
    # for curr_points
    for i in range(K):
        curr_points += arr[i]
 
    # Update value for max_points
    max_points = curr_points
 
    # j points to the end of the array
    j = size - 1
 
    for i in range(K - 1, -1, -1):
        curr_points = (curr_points +
                       arr[j] - arr[i])
        max_points = max(curr_points,
                         max_points)
        j -= 1
 
    # Return the final result
    return max_points
 
# Driver code
if __name__ == "__main__":
     
    arr = [ 8, 4, 4, 8, 12, 3, 2, 9 ]
    K = 3
    n = len(arr)
 
    print(maxPointCount(arr, K, n))
 
# This code is contributed by chitranayal

C#

// C# program to maximize the sum
// of K elements in the array by
// taking only corner elements
using System;
class GFG{
 
// Function to return maximum sum
public static int maxPointCount(int []arr,
                                int K,
                                int size)
{
     
    // Initialse variables
    int curr_points = 0;
    int max_points = 0;
 
    // Iterate over first K elements
    // of array and update the value
    // for curr_points
    for(int i = 0; i < K; i++)
        curr_points += arr[i];
 
    // Update value for max_points
    max_points = curr_points;
 
    // j points to the end of the array
    int j = size - 1;
 
    for(int i = K - 1; i >= 0; i--)
    {
        curr_points = curr_points +
                      arr[j] - arr[i];
        max_points = Math.Max(curr_points,
                              max_points);
        j--;
    }
 
    // Return the readonly result
    return max_points;
}
 
// Driver code
public static void Main(String []args)
{
    int []arr = { 8, 4, 4, 8, 12, 3, 2, 9 };
    int K = 3;
    int n = arr.Length;
 
    Console.Write( maxPointCount(arr, K, n));
}
}
 
// This code is contributed by sapnasingh4991
输出
21

时间复杂度: O(N) ,其中N是数组的大小。
辅助空间复杂度: O(1)