📌  相关文章
📜  一个数组的最长唯一子数组,在另一个数组中具有最大和

📅  最后修改于: 2022-05-13 01:56:08.957000             🧑  作者: Mango

一个数组的最长唯一子数组,在另一个数组中具有最大和

给定两个大小为N的数组X[]Y[] ,任务是在X[]中找到最长的子数组,其中只包含唯一值,这样在Y[]中具有相似索引的子数组应该具有最大 sum 。数组元素的值在[0, 1000]范围内。

例子

朴素的方法:这个任务可以通过生成数组X[]的所有数组来解决,检查每个子数组是否有效,然后计算数组中Y中对应索引总和

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

高效方法:可以使用滑动窗口的概念来解决任务。请按照以下步骤解决问题:

  • 创建一个大小为 1001 的数组m并将所有元素初始化为-1 。对于索引im[i]存储子数组中i所在的索引。如果m[i]为 -1,则表示该元素不存在于子数组中。
  • 初始化low = 0, high = 0 ,这两个指针将定义当前子数组的索引。
  • currSummaxSum ,定义当前子数组的和与数组中的最大和。
  • 遍历一个循环并检查索引的当前元素是否已经存在于子数组中,如果它确实找到了子数组中元素的总和,则更新maxSum (如果需要)并更新低。现在,最后,通过递增high移动到下一个元素。
  • 请注意,您将遇到可能导致错误答案的极端情况,例如,让我们考虑我们的第一个输入,然后子数组 {8, 2} 是正确的选择,而 30 是我们的正确答案。因此,通过对从前一个lowhigh的所有元素求和来分别处理这种极端情况。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the max sum
int findMaxSumSubarray(int X[], int Y[],
                       int N)
{
    // Array to store the elements
    // and their indices
    int m[1001];
 
    // Initialize all elements as -1
    for (int i = 0; i < 1001; i++)
        m[i] = -1;
 
    // low and high represent
    // beginning and end of subarray
    int low = 0, high = 0;
    int currSum = 0, maxSum = 0;
 
    // Iterate through the array
    // Note that the array is traversed till high <= N
    // so that the corner case can be handled
    while (high <= N) {
      if(high==N){
        //Calculate the currSum for the subarray
        //after the last updated low to high-1
        currSum=0;
        for (int i = low; i <= high - 1;
                 i++)
                currSum += Y[i];
 
            // Find the maximum sum
            maxSum = max(maxSum, currSum);
        break;
      }
        // If the current element already
        // exists in the current subarray
        if (m[X[high]] != -1
            && m[X[high]] >= low) {
            currSum = 0;
 
            // Calculate the sum
            // of current subarray
            for (int i = low; i <= high - 1;
                 i++)
                currSum += Y[i];
 
            // Find the maximum sum
            maxSum = max(maxSum, currSum);
 
            // Starting index of new subarray
            low = m[X[high]] + 1;
        }
 
        // Keep expanding the subarray
        // and mark the index
        m[X[high]] = high;
        high++;
    }
 
    // Return the maxSum
    return maxSum;
}
 
// Driver code
int main()
{
    int X[] = { 0, 1, 2, 0, 2 };
    int Y[] = { 5, 6, 7, 8, 22 };
    int N = sizeof(X) / sizeof(X[0]);
 
    // Function call to find the sum
    int maxSum = findMaxSumSubarray(X, Y, N);
 
    // Print the result
    cout << maxSum << endl;
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
public class GFG
{
 
  // Function to find the max sum
  static int findMaxSumSubarray(int X[], int Y[],
                                int N)
  {
 
    // Array to store the elements
    // and their indices
    int m[] = new int[1001];
 
    // Initialize all elements as -1
    for (int i = 0; i < 1001; i++)
      m[i] = -1;
 
    // low and high represent
    // beginning and end of subarray
    int low = 0, high = 0;
    int currSum = 0, maxSum = 0;
 
    // Iterate through the array
    // Note that the array is traversed till high <= N
    // so that the corner case can be handled
    while (high <= N) {
      if(high==N){
           // Calculate the currSum for the subarray
        // after the last updated low to high-1
        currSum = 0;
        for (int i = low; i <= high - 1;i++)
             currSum += Y[i];
        // Find the maximum sum
        maxSum = Math.max(maxSum, currSum);
        break;
      }
      // If the current element already
      // exists in the current subarray
      if (m[X[high]] != -1
          && m[X[high]] >= low) {
        currSum = 0;
 
        // Calculate the sum
        // of current subarray
        for (int i = low; i <= high - 1;
             i++)
          currSum += Y[i];
 
        // Find the maximum sum
        maxSum = Math.max(maxSum, currSum);
 
        // Starting index of new subarray
        low = m[X[high]] + 1;
      }
 
      // Keep expanding the subarray
      // and mark the index
      m[X[high]] = high;
      high++;
    }
 
    // Return the maxSum
    return maxSum;
  }
 
  // Driver code
  public static void main(String args[])
  {
    int X[] = { 0, 1, 2, 0, 2 };
    int Y[] = { 5, 6, 7, 8, 22 };
    int N = X.length;
 
    // Function call to find the sum
    int maxSum = findMaxSumSubarray(X, Y, N);
 
    // Print the result
    System.out.println(maxSum);
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Python3
# Python code for the above approach
 
# Function to find the max sum
def findMaxSumSubarray(X, Y, N):
 
    # Array to store the elements
    # and their indices
    m = [0] * (1001);
 
    # Initialize all elements as -1
    for i in range(1001):
        m[i] = -1;
 
    # low and high represent
    # beginning and end of subarray
    low = 0
    high = 0
    currSum = 0
    maxSum = 0;
 
    # Iterate through the array
    # Note that the array is traversed till high <= N
    # so that the corner case can be handled
    while (high <= N):
        if(high == N):
            currSum=0;
            # Calculate the currSum for the subarray
            # after the last updated low to high-1
            for i in range(low, high):
                currSum += Y[i];
            maxSum = max(maxSum, currSum);
            break;
     
        # If the current element already
        # exists in the current subarray
        if (m[X[high]] != -1 and m[X[high]] >= low):
            currSum = 0;
 
            # Calculate the sum
            # of current subarray
            for i in range(low, high):
                currSum += Y[i];
 
            # Find the maximum sum
            maxSum = max(maxSum, currSum);
 
            # Starting index of new subarray
            low = m[X[high]] + 1;
         
 
        # Keep expanding the subarray
        # and mark the index
        m[X[high]] = high;
        high += 1
     
 
    # Return the maxSum
    return maxSum;
 
 
# Driver code
X = [0, 1, 2, 0, 2];
Y = [5, 6, 7, 8, 22];
N = len(X)
 
# Function call to find the sum
maxSum = findMaxSumSubarray(X, Y, N);
 
# Print the result
print(maxSum, end="")
 
# This code is contributed by Saurabh Jaiswal


C#
// C# program for above approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Function to find the max sum
  static int findMaxSumSubarray(int[] X, int[] Y, int N)
  {
     
    // Array to store the elements
    // and their indices
    int[] m = new int[1001];
     
    // Initialize all elements as -1
    for (int i = 0; i < 1001; i++)
      m[i] = -1;
 
    // low and high represent
    // beginning and end of subarray
    int low = 0, high = 0;
    int currSum = 0, maxSum = 0;
 
    // Iterate through the array
    // Note that the array is traversed till high <= N
    // so that the corner case can be handled
    while (high <= N)
    {
      if(high==N){
        // Calculate the currSum for the subarray
        // after the last updated low to high-1
        currSum=0;
        for (int i = low; i <= high - 1;
             i++)
          currSum += Y[i];
 
        // Find the maximum sum
        maxSum = Math.Max(maxSum, currSum);
        break;
      }
 
      // If the current element already
      // exists in the current subarray
      if (m[X[high]] != -1
          && m[X[high]] >= low) {
        currSum = 0;
 
        // Calculate the sum
        // of current subarray
        for (int i = low; i <= high - 1;
             i++)
          currSum += Y[i];
 
        // Find the maximum sum
        maxSum = Math.Max(maxSum, currSum);
 
        // Starting index of new subarray
        low = m[X[high]] + 1;
      }
 
      // Keep expanding the subarray
      // and mark the index
      m[X[high]] = high;
      high++;
    }
 
    // Return the maxSum
    return maxSum;
  }
 
  // Driver code
  static public void Main ()
  {
 
    int[] X = { 0, 1, 2, 0, 2 };
    int[] Y = { 5, 6, 7, 8, 22 };
    int N = X.Length;
 
    // Function call to find the sum
    int maxSum = findMaxSumSubarray(X, Y, N);
 
    // Print the result
    Console.WriteLine(maxSum);
  }
}
 
// This code is contributed by hrithikgarg03188.


Javascript


输出
30

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