📌  相关文章
📜  由与给定数组相同数量的不同元素组成的 K 长度子数组的最大总和

📅  最后修改于: 2021-09-05 11:44:08             🧑  作者: Mango

给定一个由N 个整数和一个整数K组成的数组arr[] ,任务是找到一个大小为 K的子数组,其最大和和不同元素的计数与原始数组相同。

例子:

朴素的方法:简单的方法是生成大小为 K 的所有可能的子数组,并检查它是否与原始数组具有相同的不同元素。如果是,则找到该子数组的总和。检查所有子数组后,打印所有此类子数组的最大和。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count the number of
// distinct elements present in the array
int distinct(int arr[], int n)
{
    map mpp;
 
    // Insert all elements into the Set
    for (int i = 0; i < n; i++)
    {
        mpp[arr[i]] = 1;
    }
 
    // Return the size of set
    return mpp.size();
}
 
// Function that finds the maximum
// sum of K-length subarray having
// same unique elements as arr[]
int maxSubSum(int arr[], int n,int k, int totalDistinct)
{
   
    // Not possible to find a
    // subarray of size K
    if (k > n)
        return 0;
    int maxm = 0, sum = 0;
    for (int i = 0; i < n - k + 1; i++)
    {
        sum = 0;
 
        // Initialize Set
        set st;
 
        // Caluclate sum of the distinct elements
        for (int j = i; j < i + k; j++)
        {
            sum += arr[j];
            st.insert(arr[j]);
        }
 
        // If the set size is same as the
        // count of distinct elements
        if ((int) st.size() == totalDistinct)
 
            // Update the maximum value
            maxm = max(sum, maxm);
    }
    return maxm;
}
 
// Driver code
int main()
{
  int arr[] = { 7, 7, 2, 4, 2,
                7, 4, 6, 6, 6 };
  int K = 6;
  int N = sizeof(arr)/sizeof(arr[0]);
 
  // Stores the count of distinct elements
  int totalDistinct = distinct(arr, N);
  cout << (maxSubSum(arr, N, K, totalDistinct));
 
  return 0;
}
 
// This code is contributed by mohit kumar 29.


Java
// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to count the number of
    // distinct elements present in the array
    static int distinct(int arr[], int n)
    {
        Set set = new HashSet<>();
 
        // Insert all elements into the Set
        for (int i = 0; i < n; i++) {
            set.add(arr[i]);
        }
 
        // Return the size of set
        return set.size();
    }
 
    // Function that finds the maximum
    // sum of K-length subarray having
    // same unique elements as arr[]
    static int maxSubSum(int arr[], int n,
                         int k,
                         int totalDistinct)
    {
        // Not possible to find a
        // subarray of size K
        if (k > n)
            return 0;
 
        int max = 0, sum = 0;
 
        for (int i = 0; i < n - k + 1; i++) {
            sum = 0;
 
            // Initialize Set
            Set set = new HashSet<>();
 
            // Caluclate sum of the distinct elements
            for (int j = i; j < i + k; j++) {
                sum += arr[j];
                set.add(arr[j]);
            }
 
            // If the set size is same as the
            // count of distinct elements
            if (set.size() == totalDistinct)
 
                // Update the maximum value
                max = Math.max(sum, max);
        }
        return max;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int arr[] = { 7, 7, 2, 4, 2,
                      7, 4, 6, 6, 6 };
        int K = 6;
        int N = arr.length;
 
        // Stores the count of distinct elements
        int totalDistinct = distinct(arr, N);
 
        System.out.println(
            maxSubSum(arr, N, K, totalDistinct));
    }
}


Python3
# Python3 program for the above approach
 
# Function to count the number of
# distinct elements present in the array
def distinct(arr, n):
     
    mpp = {}
 
    # Insert all elements into the Set
    for i in range(n):
        mpp[arr[i]] = 1
 
    # Return the size of set
    return len(mpp)
 
# Function that finds the maximum
# sum of K-length subarray having
# same unique elements as arr[]
def maxSubSum(arr, n, k, totalDistinct):
     
    # Not possible to find a
    # subarray of size K
    if (k > n):
        return 0
         
    maxm = 0
    sum = 0
     
    for i in range(n - k + 1):
        sum = 0
 
        # Initialize Set
        st = set()
 
        # Caluclate sum of the distinct elements
        for j in range(i, i + k, 1):
            sum += arr[j]
            st.add(arr[j])
 
        # If the set size is same as the
        # count of distinct elements
        if (len(st) == totalDistinct):
             
            # Update the maximum value
            maxm = max(sum, maxm)
 
    return maxm
 
# Driver code
if __name__ == '__main__':
     
    arr = [ 7, 7, 2, 4, 2, 7, 4, 6, 6, 6 ]
    K = 6
    N = len(arr)
 
    # Stores the count of distinct elements
    totalDistinct = distinct(arr, N)
    print(maxSubSum(arr, N, K, totalDistinct))
 
# This code is contributed by ipg2016107


C#
// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
 
  // Function to count the number of
  // distinct elements present in the array
  static int distinct(int[] arr, int n)
  {
    HashSet set = new HashSet();
 
    // Insert all elements into the Set
    for (int i = 0; i < n; i++) {
      set.Add(arr[i]);
    }
 
    // Return the size of set
    return set.Count;
  }
 
  // Function that finds the maximum
  // sum of K-length subarray having
  // same unique elements as arr[]
  static int maxSubSum(int[] arr, int n,
                       int k,
                       int totalDistinct)
  {
    // Not possible to find a
    // subarray of size K
    if (k > n)
      return 0;
 
    int max = 0, sum = 0;
 
    for (int i = 0; i < n - k + 1; i++) {
      sum = 0;
 
      // Initialize Set
      HashSet set = new HashSet();
 
      // Caluclate sum of the distinct elements
      for (int j = i; j < i + k; j++) {
        sum += arr[j];
        set.Add(arr[j]);
      }
 
      // If the set size is same as the
      // count of distinct elements
      if (set.Count == totalDistinct)
 
        // Update the maximum value
        max = Math.Max(sum, max);
    }
    return max;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int[] arr = { 7, 7, 2, 4, 2,
                 7, 4, 6, 6, 6 };
    int K = 6;
    int N = arr.Length;
 
    // Stores the count of distinct elements
    int totalDistinct = distinct(arr, N);
 
    Console.WriteLine(
      maxSubSum(arr, N, K, totalDistinct));
  }
}
 
// This code is contributed by code_hunt.


Javascript


C++
// C++ program for the above approach
#include
using namespace std;
 
// Function to count the number of
// distinct elements present in the array
int distinct(vectorarr, int N)
{
    set st;
     
    // Insert array elements into set
    for(int i = 0; i < N; i++)
    {
        st.insert(arr[i]);
    }
 
    // Return the st size
    return st.size();
}
 
// Function to calculate maximum
// sum of K-length subarray having
// same unique elements as arr[]
int maxSubarraySumUtil(vectorarr, int N,
                       int K, int totalDistinct)
{
     
    // Not possible to find an
    // subarray of length K from
    // an N-sized array, if K > N
    if (K > N)
        return 0;
 
    int mx = 0;
    int sum = 0;
 
    map mp;
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Update the mp
        mp[arr[i]] += 1;
        sum += arr[i];
 
        // If i >= K, then decrement
        // arr[i-K] element's one
        // occurence
        if (i >= K)
        {
            mp[arr[i - K]] -= 1;
            sum -= arr[i - K];
 
            // If frequency of any
            // element is 0 then
            // remove the element
            if (mp[arr[i - K]] == 0)
                mp.erase(arr[i - K]);
        }
 
        // If mp size is same as the
        // count of distinct elements
        // of array arr[] then update
        // maximum sum
        if (mp.size() == totalDistinct)
            mx = max(mx, sum);
    }
    return mx;
}
 
// Function that finds the maximum
// sum of K-length subarray having
// same number of distinct elements
// as the original array
void maxSubarraySum(vectorarr,
                           int K)
{
    // Size of array
    int N = arr.size();
 
    // Stores count of distinct elements
    int totalDistinct = distinct(arr, N);
 
    // Print maximum subarray sum
    cout<arr { 7, 7, 2, 4, 2,
                     7, 4, 6, 6, 6 };
    int K = 6;
 
    // Function Call
    maxSubarraySum(arr, K);
}
 
// This code is contributed by ipg2016107


Java
// Java program for the above approach
 
import java.util.*;
class GFG {
 
    // Function to count the number of
    // distinct elements present in the array
    static int distinct(int arr[], int N)
    {
        Set set = new HashSet<>();
 
        // Insert array elements into Set
        for (int i = 0; i < N; i++) {
            set.add(arr[i]);
        }
 
        // Return the Set size
        return set.size();
    }
 
    // Function to calculate maximum
    // sum of K-length subarray having
    // same unique elements as arr[]
    static int maxSubarraySumUtil(
        int arr[], int N, int K,
        int totalDistinct)
    {
        // Not possible to find an
        // subarray of length K from
        // an N-sized array, if K > N
        if (K > N)
            return 0;
 
        int max = 0;
        int sum = 0;
 
        Map map
            = new HashMap<>();
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // Update the map
            map.put(arr[i],
                    map.getOrDefault(arr[i], 0) + 1);
            sum += arr[i];
 
            // If i >= K, then decrement
            // arr[i-K] element's one
            // occurence
            if (i >= K) {
                map.put(arr[i - K],
                        map.get(arr[i - K]) - 1);
                sum -= arr[i - K];
 
                // If frequency of any
                // element is 0 then
                // remove the element
                if (map.get(arr[i - K]) == 0)
                    map.remove(arr[i - K]);
            }
 
            // If map size is same as the
            // count of distinct elements
            // of array arr[] then update
            // maximum sum
            if (map.size() == totalDistinct)
                max = Math.max(max, sum);
        }
        return max;
    }
 
    // Function that finds the maximum
    // sum of K-length subarray having
    // same number of distinct elements
    // as the original array
    static void maxSubarraySum(int arr[],
                               int K)
    {
        // Size of array
        int N = arr.length;
 
        // Stores count of distinct elements
        int totalDistinct = distinct(arr, N);
 
        // Print maximum subarray sum
        System.out.println(
            maxSubarraySumUtil(arr, N, K,
                               totalDistinct));
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int arr[] = { 7, 7, 2, 4, 2,
                      7, 4, 6, 6, 6 };
        int K = 6;
 
        // Function Call
        maxSubarraySum(arr, K);
    }
}


Python3
# Python 3 program for the above approach
 
# Function to count the number of
# distinct elements present in the array
def distinct(arr, N):
    st = set()
     
    # Insert array elements into set
    for i in range(N):
        st.add(arr[i])
 
    # Return the st size
    return len(st)
 
# Function to calculate maximum
# sum of K-length subarray having
# same unique elements as arr[]
def maxSubarraySumUtil(arr, N, K, totalDistinct):
    # Not possible to find an
    # subarray of length K from
    # an N-sized array, if K > N
    if (K > N):
        return 0
 
    mx = 0
    sum = 0
 
    mp = {}
 
    # Traverse the array
    for i in range(N):
        # Update the mp
        if(arr[i] in mp):
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
        sum += arr[i]
 
        # If i >= K, then decrement
        # arr[i-K] element's one
        # occurence
        if (i >= K):
            if(arr[i-K] in mp):
                mp[arr[i - K]] -= 1
                sum -= arr[i - K]
 
            # If frequency of any
            # element is 0 then
            # remove the element
            if (arr[i-K] in mp and mp[arr[i - K]] == 0):
                mp.remove(arr[i - K])
 
        # If mp size is same as the
        # count of distinct elements
        # of array arr[] then update
        # maximum sum
        if (len(mp) == totalDistinct):
            mx = max(mx, sum)
    return mx
 
# Function that finds the maximum
# sum of K-length subarray having
# same number of distinct elements
# as the original array
def maxSubarraySum(arr, K):
   
    # Size of array
    N = len(arr)
 
    # Stores count of distinct elements
    totalDistinct = distinct(arr, N)
 
    # Print maximum subarray sum
    print(maxSubarraySumUtil(arr, N, K, totalDistinct))
 
# Driver Code
if __name__ == '__main__':
    arr  =  [7, 7, 2, 4, 2,7, 4, 6, 6, 6]
    K = 6
 
    # Function Call
    maxSubarraySum(arr, K)
 
    # This code is contributed by SURENDRA_GANGWAR.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
  
// Function to count the number of
// distinct elements present in the array
static int distinct(Listarr, int N)
{
    HashSet st = new HashSet();
     
    // Insert array elements into set
    for(int i = 0; i < N; i++)
    {
        st.Add(arr[i]);
    }
 
    // Return the st size
    return st.Count;
}
 
// Function to calculate maximum
// sum of K-length subarray having
// same unique elements as arr[]
static int maxSubarraySumUtil(Listarr, int N,
                       int K, int totalDistinct)
{
     
    // Not possible to find an
    // subarray of length K from
    // an N-sized array, if K > N
    if (K > N)
        return 0;
    int mx = 0;
    int sum = 0; 
    Dictionary mp = new Dictionary();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Update the mp
        if(mp.ContainsKey(arr[i]))
            mp[arr[i]] += 1;
        else
            mp[arr[i]] = 1;
        sum += arr[i];
 
        // If i >= K, then decrement
        // arr[i-K] element's one
        // occurence
        if (i >= K)
        {
           if(mp.ContainsKey(arr[i - K]))
              mp[arr[i - K]] -= 1;
           else
              mp[arr[i - K]] = 1;
            sum -= arr[i - K];
 
            // If frequency of any
            // element is 0 then
            // remove the element
            if (mp[arr[i - K]] == 0)
                mp.Remove(arr[i - K]);
        }
 
        // If mp size is same as the
        // count of distinct elements
        // of array arr[] then update
        // maximum sum
        if (mp.Count == totalDistinct)
            mx = Math.Max(mx, sum);
    }
    return mx;
}
 
// Function that finds the maximum
// sum of K-length subarray having
// same number of distinct elements
// as the original array
static void maxSubarraySum(Listarr,
                           int K)
{
   
    // Size of array
    int N = arr.Count;
 
    // Stores count of distinct elements
    int totalDistinct = distinct(arr, N);
 
    // Print maximum subarray sum
    Console.WriteLine(maxSubarraySumUtil(arr, N, K, totalDistinct));
}
 
// Driver Code
public static void Main()
{
    Listarr = new List{ 7, 7, 2, 4, 2,
                     7, 4, 6, 6, 6 };
    int K = 6;
 
    // Function Call
    maxSubarraySum(arr, K);
}
}
 
// This code is contributed by bgangwar59.


输出:
31

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

高效的方法:为了优化上述方法,思想是利用Map。请按照以下步骤解决问题:

  1. 遍历数组一次,并不断更新Map中数组元素的频率。
  2. 检查地图的大小是否等于原始数组中存在的不同元素的总数。如果发现为真,则更新最大总和。
  3. 在遍历原始数组时,如果第i遍历穿过数组中的K 个元素,则通过删除(i – K)元素的出现来更新Map
  4. 完成上述步骤后,打印得到的最大和。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include
using namespace std;
 
// Function to count the number of
// distinct elements present in the array
int distinct(vectorarr, int N)
{
    set st;
     
    // Insert array elements into set
    for(int i = 0; i < N; i++)
    {
        st.insert(arr[i]);
    }
 
    // Return the st size
    return st.size();
}
 
// Function to calculate maximum
// sum of K-length subarray having
// same unique elements as arr[]
int maxSubarraySumUtil(vectorarr, int N,
                       int K, int totalDistinct)
{
     
    // Not possible to find an
    // subarray of length K from
    // an N-sized array, if K > N
    if (K > N)
        return 0;
 
    int mx = 0;
    int sum = 0;
 
    map mp;
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Update the mp
        mp[arr[i]] += 1;
        sum += arr[i];
 
        // If i >= K, then decrement
        // arr[i-K] element's one
        // occurence
        if (i >= K)
        {
            mp[arr[i - K]] -= 1;
            sum -= arr[i - K];
 
            // If frequency of any
            // element is 0 then
            // remove the element
            if (mp[arr[i - K]] == 0)
                mp.erase(arr[i - K]);
        }
 
        // If mp size is same as the
        // count of distinct elements
        // of array arr[] then update
        // maximum sum
        if (mp.size() == totalDistinct)
            mx = max(mx, sum);
    }
    return mx;
}
 
// Function that finds the maximum
// sum of K-length subarray having
// same number of distinct elements
// as the original array
void maxSubarraySum(vectorarr,
                           int K)
{
    // Size of array
    int N = arr.size();
 
    // Stores count of distinct elements
    int totalDistinct = distinct(arr, N);
 
    // Print maximum subarray sum
    cout<arr { 7, 7, 2, 4, 2,
                     7, 4, 6, 6, 6 };
    int K = 6;
 
    // Function Call
    maxSubarraySum(arr, K);
}
 
// This code is contributed by ipg2016107

Java

// Java program for the above approach
 
import java.util.*;
class GFG {
 
    // Function to count the number of
    // distinct elements present in the array
    static int distinct(int arr[], int N)
    {
        Set set = new HashSet<>();
 
        // Insert array elements into Set
        for (int i = 0; i < N; i++) {
            set.add(arr[i]);
        }
 
        // Return the Set size
        return set.size();
    }
 
    // Function to calculate maximum
    // sum of K-length subarray having
    // same unique elements as arr[]
    static int maxSubarraySumUtil(
        int arr[], int N, int K,
        int totalDistinct)
    {
        // Not possible to find an
        // subarray of length K from
        // an N-sized array, if K > N
        if (K > N)
            return 0;
 
        int max = 0;
        int sum = 0;
 
        Map map
            = new HashMap<>();
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // Update the map
            map.put(arr[i],
                    map.getOrDefault(arr[i], 0) + 1);
            sum += arr[i];
 
            // If i >= K, then decrement
            // arr[i-K] element's one
            // occurence
            if (i >= K) {
                map.put(arr[i - K],
                        map.get(arr[i - K]) - 1);
                sum -= arr[i - K];
 
                // If frequency of any
                // element is 0 then
                // remove the element
                if (map.get(arr[i - K]) == 0)
                    map.remove(arr[i - K]);
            }
 
            // If map size is same as the
            // count of distinct elements
            // of array arr[] then update
            // maximum sum
            if (map.size() == totalDistinct)
                max = Math.max(max, sum);
        }
        return max;
    }
 
    // Function that finds the maximum
    // sum of K-length subarray having
    // same number of distinct elements
    // as the original array
    static void maxSubarraySum(int arr[],
                               int K)
    {
        // Size of array
        int N = arr.length;
 
        // Stores count of distinct elements
        int totalDistinct = distinct(arr, N);
 
        // Print maximum subarray sum
        System.out.println(
            maxSubarraySumUtil(arr, N, K,
                               totalDistinct));
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int arr[] = { 7, 7, 2, 4, 2,
                      7, 4, 6, 6, 6 };
        int K = 6;
 
        // Function Call
        maxSubarraySum(arr, K);
    }
}

蟒蛇3

# Python 3 program for the above approach
 
# Function to count the number of
# distinct elements present in the array
def distinct(arr, N):
    st = set()
     
    # Insert array elements into set
    for i in range(N):
        st.add(arr[i])
 
    # Return the st size
    return len(st)
 
# Function to calculate maximum
# sum of K-length subarray having
# same unique elements as arr[]
def maxSubarraySumUtil(arr, N, K, totalDistinct):
    # Not possible to find an
    # subarray of length K from
    # an N-sized array, if K > N
    if (K > N):
        return 0
 
    mx = 0
    sum = 0
 
    mp = {}
 
    # Traverse the array
    for i in range(N):
        # Update the mp
        if(arr[i] in mp):
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
        sum += arr[i]
 
        # If i >= K, then decrement
        # arr[i-K] element's one
        # occurence
        if (i >= K):
            if(arr[i-K] in mp):
                mp[arr[i - K]] -= 1
                sum -= arr[i - K]
 
            # If frequency of any
            # element is 0 then
            # remove the element
            if (arr[i-K] in mp and mp[arr[i - K]] == 0):
                mp.remove(arr[i - K])
 
        # If mp size is same as the
        # count of distinct elements
        # of array arr[] then update
        # maximum sum
        if (len(mp) == totalDistinct):
            mx = max(mx, sum)
    return mx
 
# Function that finds the maximum
# sum of K-length subarray having
# same number of distinct elements
# as the original array
def maxSubarraySum(arr, K):
   
    # Size of array
    N = len(arr)
 
    # Stores count of distinct elements
    totalDistinct = distinct(arr, N)
 
    # Print maximum subarray sum
    print(maxSubarraySumUtil(arr, N, K, totalDistinct))
 
# Driver Code
if __name__ == '__main__':
    arr  =  [7, 7, 2, 4, 2,7, 4, 6, 6, 6]
    K = 6
 
    # Function Call
    maxSubarraySum(arr, K)
 
    # This code is contributed by SURENDRA_GANGWAR.

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
  
// Function to count the number of
// distinct elements present in the array
static int distinct(Listarr, int N)
{
    HashSet st = new HashSet();
     
    // Insert array elements into set
    for(int i = 0; i < N; i++)
    {
        st.Add(arr[i]);
    }
 
    // Return the st size
    return st.Count;
}
 
// Function to calculate maximum
// sum of K-length subarray having
// same unique elements as arr[]
static int maxSubarraySumUtil(Listarr, int N,
                       int K, int totalDistinct)
{
     
    // Not possible to find an
    // subarray of length K from
    // an N-sized array, if K > N
    if (K > N)
        return 0;
    int mx = 0;
    int sum = 0; 
    Dictionary mp = new Dictionary();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Update the mp
        if(mp.ContainsKey(arr[i]))
            mp[arr[i]] += 1;
        else
            mp[arr[i]] = 1;
        sum += arr[i];
 
        // If i >= K, then decrement
        // arr[i-K] element's one
        // occurence
        if (i >= K)
        {
           if(mp.ContainsKey(arr[i - K]))
              mp[arr[i - K]] -= 1;
           else
              mp[arr[i - K]] = 1;
            sum -= arr[i - K];
 
            // If frequency of any
            // element is 0 then
            // remove the element
            if (mp[arr[i - K]] == 0)
                mp.Remove(arr[i - K]);
        }
 
        // If mp size is same as the
        // count of distinct elements
        // of array arr[] then update
        // maximum sum
        if (mp.Count == totalDistinct)
            mx = Math.Max(mx, sum);
    }
    return mx;
}
 
// Function that finds the maximum
// sum of K-length subarray having
// same number of distinct elements
// as the original array
static void maxSubarraySum(Listarr,
                           int K)
{
   
    // Size of array
    int N = arr.Count;
 
    // Stores count of distinct elements
    int totalDistinct = distinct(arr, N);
 
    // Print maximum subarray sum
    Console.WriteLine(maxSubarraySumUtil(arr, N, K, totalDistinct));
}
 
// Driver Code
public static void Main()
{
    Listarr = new List{ 7, 7, 2, 4, 2,
                     7, 4, 6, 6, 6 };
    int K = 6;
 
    // Function Call
    maxSubarraySum(arr, K);
}
}
 
// This code is contributed by bgangwar59.
输出:
31

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

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