📌  相关文章
📜  通过删除元素形成的具有相同第一个和最后一个元素的最大子数组和

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

通过删除元素形成的具有相同第一个和最后一个元素的最大子数组和

给定一个包含N个整数的数组arr[] ,任务是找到长度至少为 2且在删除任意数量的数组元素后第一个和最后一个元素相同的子数组的最大和。如果不存在这样的数组,则打印0

例子:

方法:给定的问题可以通过使用这样的想法来解决,即首先找到所有第一个和最后一个元素相同的子数组,然后删除第一个和最后一个元素之间的所有负元素。这个想法可以通过本文讨论的使用无序映射的想法来实现。请按照以下步骤解决给定的问题:

  • 初始化一个变量,比如resINT_MIN ,它存储子数组的最大总和。
  • 初始化一个变量,比如currentSum0 ,它存储数组的运行前缀总和。
  • 初始化一个 unordered_map,比如memo[] ,它存储每个数组元素的值及其前缀和。
  • 使用变量i遍历范围[0, N)并执行以下任务:
    • 将当前数组元素arr[i]的值添加到变量currentSum中。
    • 如果地图中存在arr[i] ,并且如果arr[i]的值为正,则将res的值更新为res(currentSum – M[arr[i]] + arr[i])的最大值.否则,将 res 的值更新为res(currentSum – M[arr[i]] + 2*arr[i])的最大值。
    • 否则,插入与currentSum映射的值arr[i]
    • 如果当前值arr[i]为负,则将其从currentSum中递减以排除可能子数组的负元素。
  • 完成上述步骤后,打印res的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the maximum sum
// of sub-array
int maximumSubarraySum(vector& arr)
{
 
    // Initialize the variables
    int N = arr.size();
    unordered_map memo;
    int res = INT_MIN;
    int currsum = 0, currval = 0;
 
    // Traverse over the range
    for (int i = 0; i < N; ++i) {
 
        // Add the current value to the
        // variable currsum for prefix sum
        currval = arr[i];
        currsum = currsum + currval;
 
        // Calculate the result
        if (memo.count(currval) != 0) {
            if (currval > 0)
                res = max(
                    res,
                    currsum - memo[currval]
                        + currval);
            else
                res = max(
                    res,
                    currsum - memo[currval]
                        + 2 * currval);
        }
        else
            memo[currval] = currsum;
        if (currval < 0)
            currsum = currsum - currval;
    }
 
    // Return the answer
    return res;
}
 
// Driver Code
int main()
{
    vector arr = { -1, -3, 4, 0, -1, -2 };
    cout << maximumSubarraySum(arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG
{
   
    // Function to find the maximum sum
    // of sub-array
    static int maximumSubarraySum(int arr[], int N)
    {
 
        // Initialize the variables
        HashMap memo = new HashMap<>();
        int res = Integer.MIN_VALUE;
        int currsum = 0, currval = 0;
 
        // Traverse over the range
        for (int i = 0; i < N; ++i) {
 
            // Add the current value to the
            // variable currsum for prefix sum
            currval = arr[i];
            currsum = currsum + currval;
 
            // Calculate the result
            if (memo.containsKey(currval)) {
                if (currval > 0)
                    res = Math.max(
                        res, currsum - memo.get(currval)
                                 + currval);
                else
                    res = Math.max(
                        res, currsum - memo.get(currval)
                                 + 2 * currval);
            }
            else
                memo.put(currval, currsum);
            if (currval < 0)
                currsum = currsum - currval;
        }
 
        // Return the answer
        return res;
    }
   
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { -1, -3, 4, 0, -1, -2 };
        int N = 6;
        System.out.println(maximumSubarraySum(arr, N));
    }
}
 
// This code is contributed by dwivediyash


Python3
# Python3 program for the above approach
import sys
 
# Function to find the maximum sum
# of sub-array
def maximumSubarraySum(arr) :
 
    # Initialize the variables
    N = len(arr);
    memo = {};
    res = -(sys.maxsize - 1);
    currsum = 0;
    currval = 0;
 
    # Traverse over the range
    for i in range(N) :
 
        # Add the current value to the
        # variable currsum for prefix sum
        currval = arr[i];
        currsum = currsum + currval;
 
        # Calculate the result
        if currval in memo :
             
            if (currval > 0) :
                res = max(res,currsum - memo[currval] + currval);
            else :
                res = max(res,currsum - memo[currval] + 2 * currval);
         
        else :
            memo[currval] = currsum;
             
        if (currval < 0) :
            currsum = currsum - currval;
 
    # Return the answer
    return res;
 
 
# Driver Code
if __name__ == "__main__" :
 
    arr = [ -1, -3, 4, 0, -1, -2 ];
    print(maximumSubarraySum(arr));
 
    # This code is contributed by AnkThon


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
    // Function to find the maximum sum
    // of sub-array
    static int maximumSubarraySum(int[] arr, int N)
    {
 
        // Initialize the variables
        Dictionary memo = new
                Dictionary();
        int res = Int32.MinValue;
        int currsum = 0, currval = 0;
 
        // Traverse over the range
        for (int i = 0; i < N; ++i) {
 
            // Add the current value to the
            // variable currsum for prefix sum
            currval = arr[i];
            currsum = currsum + currval;
 
            // Calculate the result
            if (memo.ContainsKey(currval)) {
                if (currval > 0)
                    res = Math.Max(
                        res, currsum - memo[(currval)]
                                 + currval);
                else
                    res = Math.Max(
                        res, currsum - memo[(currval)]
                                 + 2 * currval);
            }
            else
                memo.Add(currval, currsum);
            if (currval < 0)
                currsum = currsum - currval;
        }
 
        // Return the answer
        return res;
    }
 
// Driver Code
public static void Main()
{
    int[] arr = { -1, -3, 4, 0, -1, -2 };
    int N = 6;
    Console.WriteLine(maximumSubarraySum(arr, N));
}
}
 
// This code is contributed by sanjoy_62.


Javascript


输出:
2

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