📜  子数组中“ max + min”的最小值

📅  最后修改于: 2021-05-07 18:23:13             🧑  作者: Mango

给定n个正元素数组,鉴于子数组的大小应大于等于2,我们需要在子数组中找到max和min元素的最小和。

例子:

Input : arr[] = {1 12 2 2}
Output : 4
Sum of 2+2 of subarray [2, 2]

Input  : arr[] = {10 20 30 40 23 45}
Output : 30 
Sum of 10+20 of subarray[10, 20]

一个简单的解决方案是生成所有子数组,计算最大和最小和,最后返回最小和。

一种有效的解决方案基于以下事实:将任何元素添加到子数组都不会增加最大值和最小值之和。考虑数组[a1,a2,a3,a4,a5….an]每个ai将是某个子数组[al,ar]的最小值,这样我位于[l,r]之间并且子数组中的所有元素都大于或等于ai。这样的子阵列的成本将是ai + max(子阵列)。由于数组的最大值在将元素添加到数组中时永远不会减少,因此只有在添加更大的元素时才会增加,因此始终最好只考虑那些长度为2的子数组。

简而言之,考虑所有长度为2的子数组并比较和并取最小的子数组,这将使时间复杂度降低O(N),现在我们只需要运行一次循环。

C++
// CPP program to find sum of maximum and
// minimum in any subarray of an array of
// positive numbers.
#include 
using namespace std;
  
int maxSum(int arr[], int n)
{
    if (n < 2)
        return -1;
    int ans = arr[0] + arr[1];
    for (int i = 1; i + 1 < n; i++)
        ans = min(ans, (arr[i] + arr[i + 1]));
    return ans;
}
  
// Driver code
int main()
{
    int arr[] = {1, 12, 2, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << maxSum(arr, n);
    return 0;
}


Java
// java program to find sum of maximum and
// minimum in any subarray of an array of
// positive numbers.
import java.io.*;
  
class GFG {
      
    static int maxSum(int arr[], int n)
    {
        if (n < 2)
            return -1;
        int ans = arr[0] + arr[1];
        for (int i = 1; i + 1 < n; i++)
            ans = Math.min(ans, (arr[i] 
                           + arr[i + 1]));
        return ans;
    }
      
    // Driver code
    public static void main (String[] args) 
    {
        int arr[] = {1, 12, 2, 2};
        int n = arr.length;
          
        System.out.println( maxSum(arr, n));
    }
}
  
// This code is contributed by anuj_67.


Python 3
# Python 3 program to find sum of maximum 
# and minimum in any subarray of an array 
# of positive numbers.
  
def maxSum(arr, n):
    if (n < 2):
        return -1
    ans = arr[0] + arr[1]
    for i in range(1, n - 1, 1):
        ans = min(ans, (arr[i] + arr[i + 1]))
    return ans
  
# Driver code
if __name__ == '__main__':
    arr = [1, 12, 2, 2]
    n = len(arr)
    print(maxSum(arr, n))
  
# This code is contributed by 
# Surendra_Gangwar


C#
// C# program to find sum of maximum and
// minimum in any subarray of an array of
// positive numbers.
using System ;
  
class GFG {
      
    static int maxSum(int []arr, int n)
    {
        if (n < 2)
            return -1;
        int ans = arr[0] + arr[1];
        for (int i = 1; i + 1 < n; i++)
            ans = Math.Min(ans, (arr[i] 
                        + arr[i + 1]));
        return ans;
    }
      
    // Driver code
    public static void Main () 
    {
        int []arr = {1, 12, 2, 2};
        int n = arr.Length;
          
        Console.WriteLine( maxSum(arr, n));
    }
}
  
// This code is contributed by anuj_67.


PHP


输出:
4

时间复杂度:O(n)
辅助空间:O(1)