📌  相关文章
📜  允许混洗时,用于 Q 查询的 Array 给定范围内值的最大总和

📅  最后修改于: 2021-09-04 08:01:25             🧑  作者: Mango

给定一个数组arr[]和形式为 (L i , Ri i ) 的K个子数组,任务是找到最大可能值

\sum_{i = 1}^{K} arr[L_i:R_i]

.允许在计算此值之前对数组进行洗牌以获得最大和。

例子:

朴素的方法:一个简单的解决方案是计算给定数组的所有可能排列的最大和,并检查哪个序列给了我们最大的和。

有效的方法:这个想法是使用前缀数组来找出所有子数组的索引频率。我们可以这样做:

//Initialize an array 
prefSum[n] = {0, 0, ...0}
for each Li, Ri:
    prefSum[Li]++
    prefSum[Ri+1]--

// Find Prefix sum
for i=1 to N:
    prefSum[i] += prefSum[i-1]

// prefSum contains frequency of 
// each index over all subarrays

最后,贪婪地选择频率最高的索引,并将数组中最大的元素放在该索引处。这样我们将得到最大可能的总和。

下面是上述方法的实现:

C++
// C++ implementation to find the
// maximum sum of K subarrays
// when shuffling is allowed
 
#include 
using namespace std;
 
// Function to find the
// maximum sum of all subarrays
int maximumSubarraySum(
    int a[], int n,
    vector >& subarrays)
{
    // Initialize maxsum
    // and prefixArray
    int i, maxsum = 0;
    int prefixArray[n] = { 0 };
 
    // Find the frequency
    // using prefix Array
    for (i = 0; i < subarrays.size(); ++i) {
        prefixArray[subarrays[i].first - 1]++;
        prefixArray[subarrays[i].second]--;
    }
 
    // Perform prefix sum
    for (i = 1; i < n; i++) {
        prefixArray[i] += prefixArray[i - 1];
    }
 
    // Sort both arrays to get a greedy result
    sort(prefixArray,
        prefixArray + n,
        greater());
    sort(a, a + n, greater());
 
    // Finally multiply largest frequency with
    // largest array element.
    for (i = 0; i < n; i++)
        maxsum += a[i] * prefixArray[i];
 
    // Return the answer
    return maxsum;
}
 
// Driver Code
int main()
{
    int n = 6;
 
    // Initial Array
    int a[] = { 4, 1, 2, 1, 9, 2 };
 
    // Subarrays
    vector > subarrays;
    subarrays.push_back({ 1, 2 });
    subarrays.push_back({ 1, 3 });
    subarrays.push_back({ 1, 4 });
    subarrays.push_back({ 3, 4 });
 
    // Function Call
    cout << maximumSubarraySum(a, n,
                            subarrays);
}


Java
// Java implementation to find the
// maximum sum of K subarrays
// when shuffling is allowed
import java.util.*;
import java.lang.*;
 
class GFG{
     
// Function to find the
// maximum sum of all subarrays
static int maximumSubarraySum(int a[], int n,
           ArrayList> subarrays)
{
     
    // Initialize maxsum
    // and prefixArray
    int i, maxsum = 0;
    int[] prefixArray = new int[n];
  
    // Find the frequency
    // using prefix Array
    for(i = 0; i < subarrays.size(); ++i)
    {
        prefixArray[subarrays.get(i).get(0) - 1]++;
        prefixArray[subarrays.get(i).get(1)]--;
    }
  
    // Perform prefix sum
    for(i = 1; i < n; i++)
    {
        prefixArray[i] += prefixArray[i - 1];
    }
  
    // Sort both arrays to get a
    // greedy result
    Arrays.sort(prefixArray);
    Arrays.sort(a);
  
    // Finally multiply largest
    // frequency with largest
    // array element.
    for(i = 0; i < n; i++)
        maxsum += a[i] * prefixArray[i];
         
    // Return the answer
    return maxsum;
}
  
// Driver code
public static void main (String[] args)
{
    int n = 6;
     
    // Initial Array
    int a[] = { 4, 1, 2, 1, 9, 2 };
     
    // Subarrays
    ArrayList> subarrays = new ArrayList<>();
    subarrays.add(Arrays.asList(1, 2));
    subarrays.add(Arrays.asList(1, 3));
    subarrays.add(Arrays.asList(1, 4));
    subarrays.add(Arrays.asList(3, 4));
     
    // Function call
    System.out.println(maximumSubarraySum(a, n,
                                          subarrays));
}
}
 
// This code is contributed by offbeat


Python3
# Python3 implementation to find the
# maximum sum of K subarrays
# when shuffling is allowed
 
# Function to find the
# maximum sum of all subarrays
def maximumSubarraySum(a, n, subarrays):
 
    # Initialize maxsum
    # and prefixArray
    maxsum = 0
    prefixArray = [0] * n
 
    # Find the frequency
    # using prefix Array
    for i in range(len(subarrays)):
        prefixArray[subarrays[i][0] - 1] += 1
        prefixArray[subarrays[i][1]] -= 1
 
    # Perform prefix sum
    for i in range(1, n):
        prefixArray[i] += prefixArray[i - 1]
 
    # Sort both arrays to get a greedy result
    prefixArray.sort()
    prefixArray.reverse()
    a.sort()
    a.reverse()
 
    # Finally multiply largest frequency with
    # largest array element.
    for i in range(n):
        maxsum += a[i] * prefixArray[i]
 
    # Return the answer
    return maxsum
 
# Driver Code
n = 6
 
# Initial Array
a = [ 4, 1, 2, 1, 9, 2 ]
 
# Subarrays
subarrays = [ [ 1, 2 ], [ 1, 3 ],
              [ 1, 4 ], [ 3, 4 ] ]
 
# Function Call
print(maximumSubarraySum(a, n, subarrays))
 
# This code is contributed by divyeshrabadiya07


C#
// C# implementation to find the
// maximum sum of K subarrays
// when shuffling is allowed
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find the
// maximum sum of all subarrays
static int maximumSubarraySum(int[] a, int n,
                    List> subarrays)
{
     
    // Initialize maxsum
    // and prefixArray
    int i, maxsum = 0;
    int[] prefixArray = new int[n];
   
    // Find the frequency
    // using prefix Array
    for(i = 0; i < subarrays.Count; ++i)
    {
        prefixArray[subarrays[i][0] - 1]++;
        prefixArray[subarrays[i][1]]--;
    }
   
    // Perform prefix sum
    for(i = 1; i < n; i++)
    {
        prefixArray[i] += prefixArray[i - 1];
    }
   
    // Sort both arrays to get a
    // greedy result
    Array.Sort(prefixArray);
    Array.Sort(a);
   
    // Finally multiply largest
    // frequency with largest
    // array element.
    for(i = 0; i < n; i++)
        maxsum += a[i] * prefixArray[i];
          
    // Return the answer
    return maxsum;
}
 
// Driver Code
static void Main()
{
    int n = 6;
     
    // Initial Array
    int[] a = { 4, 1, 2, 1, 9, 2 };
      
    // Subarrays
    List> subarrays = new List>();
    subarrays.Add(new List{ 1, 2 });
    subarrays.Add(new List{ 1, 3 });
    subarrays.Add(new List{ 1, 4 });
    subarrays.Add(new List{ 3, 4 });
      
    // Function call
    Console.WriteLine(maximumSubarraySum(a, n,subarrays));
}
}
 
// This code is contributed by divyesh072019


Javascript


输出:
49

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live