📌  相关文章
📜  通过在偶数大小的子数组上右移获得的偶数索引元素的最大和

📅  最后修改于: 2021-04-27 16:54:20             🧑  作者: Mango

给定数组arr [] ,我们需要找到偶数索引元素的最大和,可以通过对偶数长度乘以1的任何子数组执行右移运算来获得最大和。

例子:

朴素的方法:朴素的方法是将每个可能的偶数长度的子数组右移一个,并在每次可能的子数组移动后找到所有数组的偶数索引处的元素之和。所有数组中的最大和是所需的结果。

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

高效方法:为了优化上述朴素方法,我们可以观察到,在对任何偶数子数组执行右移1之后,奇数索引值将被偶数索引值代替,反之亦然。如果我们在移位之前找到偶数索引处的元素之和(例如sum ),那么在移位后,总和会被偶数索引和奇数索引处元素之间的连续差之和改变。
例如:

我们将使用以上概念来解决此问题。步骤如下:

  1. 创建两个数组(例如arr1 []arr2 [] ),以使arr1 []将元素的连续差值存储在数组arr []中,如下所示:
    {(a[1] – a[0]), (a[3] – a[2]), . . ., (a[n]-a[n-1])}
    

    并且arr2 []将元素在数组arr []中的连续差存储为:

    {(a[1] – a[2]), (a[3] – a[4]), . . ., (a[n-1]-a[n])}
    
  2. 然后在上面形成的两个数组中使用Kadane算法找到最大子数组总和。
  3. 现在,最大和为原始数组( arr [] )中偶数索引处的元素之和+两个数组arr1 []arr2 []的最大子数组和。

下面是上述方法的实现:

C++
// C++ program for the above approach 
#include  
using namespace std; 
  
// Kadane's Algorithm to find 
// the maximum sum sub array 
int kadane(vector v) 
{ 
    int maxSoFar = 0; 
    int maxEndingHere = 0; 
  
    // Iterate array v 
    for (int i = 0; i < v.size(); i++) { 
  
        maxEndingHere += v[i]; 
  
        // Update the maximum 
        maxSoFar = max(maxEndingHere, 
                    maxSoFar); 
  
        // Update maxEndingHere to 0 if it 
        // is less than 0 
        maxEndingHere 
            = max(maxEndingHere, 0); 
    } 
  
    // Return maximum sum 
    return maxSoFar; 
} 
  
// Function to find the sum 
// of even indexed elements 
// after modification in array. 
int sumOfElements(int* arr, int n) 
{ 
    int sum = 0; 
  
    // Find initial sum of 
    // even indexed elements 
    for (int i = 0; i < n; i++) { 
        if (i % 2 == 0) 
            sum += arr[i]; 
    } 
  
    // Create two vectors to store 
    // the consecutive differences 
    // of elements 
    vector v1; 
    vector v2; 
  
    for (int i = 1; i < n; i += 2) { 
  
        v1.push_back(arr[i] 
                    - arr[i - 1]); 
  
        if (i + 1 < n) { 
            v2.push_back(arr[i] 
                        - arr[i + 1]); 
        } 
    } 
  
    // Find the maximum sum subarray 
    int option1 = kadane(v1); 
    int option2 = kadane(v2); 
  
    // Add the maximum value 
    // to initial sum 
    int ans = sum + max(option1, 
                        option2); 
  
    // Return the answer 
    return ans; 
} 
  
// Driver Code 
int main() 
{ 
    // Given array arr[] 
    int arr[] = { 5, 1, 3, 4, 5, 6 }; 
  
    int N = sizeof(arr) / sizeof(arr[0]); 
  
    // Function Call 
    cout << sumOfElements(arr, N); 
    return 0; 
}


Java
// Java program for the above approach 
import java.util.*; 
  
class GFG{ 
  
// Kadane's Algorithm to find 
// the maximum sum sub array 
static int kadane(Vector v) 
{ 
    int maxSoFar = 0; 
    int maxEndingHere = 0; 
  
    // Iterate array v 
    for(int i = 0; i < v.size(); i++) 
    { 
    maxEndingHere += v.get(i); 
          
    // Update the maximum 
    maxSoFar = Math.max(maxEndingHere, 
                        maxSoFar); 
          
    // Update maxEndingHere to 0 if it 
    // is less than 0 
    maxEndingHere = Math.max(maxEndingHere, 0); 
    } 
      
    // Return maximum sum 
    return maxSoFar; 
} 
  
// Function to find the sum 
// of even indexed elements 
// after modification in array. 
static int sumOfElements(int []arr, int n) 
{ 
    int sum = 0; 
  
    // Find initial sum of 
    // even indexed elements 
    for(int i = 0; i < n; i++) 
    { 
    if (i % 2 == 0) 
        sum += arr[i]; 
    } 
  
    // Create two vectors to store 
    // the consecutive differences 
    // of elements 
    Vector v1 = new Vector(); 
    Vector v2 = new Vector(); 
  
    for(int i = 1; i < n; i += 2) 
    { 
    v1.add(arr[i] - arr[i - 1]); 
          
    if (i + 1 < n) 
    { 
        v2.add(arr[i] - arr[i + 1]); 
    } 
    } 
      
    // Find the maximum sum subarray 
    int option1 = kadane(v1); 
    int option2 = kadane(v2); 
  
    // Add the maximum value 
    // to initial sum 
    int ans = sum + Math.max(option1, 
                            option2); 
  
    // Return the answer 
    return ans; 
} 
  
// Driver Code 
public static void main(String[] args) 
{ 
      
    // Given array arr[] 
    int arr[] = { 5, 1, 3, 4, 5, 6 }; 
  
    int N = arr.length; 
  
    // Function Call 
    System.out.print(sumOfElements(arr, N)); 
} 
} 
  
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach 
  
# Kadane's Algorithm to find 
# the maximum sum sub array 
def kadane(v): 
  
    maxSoFar = 0; 
    maxEndingHere = 0; 
  
    # Iterate array v 
    for i in range(len(v)): 
        maxEndingHere += v[i]; 
  
        # Update the maximum 
        maxSoFar = max(maxEndingHere, 
                    maxSoFar); 
  
        # Update maxEndingHere to 0 
        # if it is less than 0 
        maxEndingHere = max(maxEndingHere, 0); 
  
    # Return maximum sum 
    return maxSoFar; 
  
# Function to find the sum 
# of even indexed elements 
# after modification in array. 
def sumOfElements(arr, n): 
  
    sum = 0; 
  
    # Find initial sum of 
    # even indexed elements 
    for i in range(n): 
        if (i % 2 == 0): 
            sum += arr[i]; 
  
    # Create two vectors to store 
    # the consecutive differences 
    # of elements 
    v1 = []; 
    v2 = []; 
  
    for i in range(1, n, 2): 
        v1.append(arr[i] - arr[i - 1]); 
  
        if (i + 1 < n): 
            v2.append(arr[i] - arr[i + 1]); 
  
    # Find the maximum sum subarray 
    option1 = kadane(v1); 
    option2 = kadane(v2); 
  
    # Add the maximum value 
    # to initial sum 
    ans = sum + max(option1, option2); 
  
    # Return the answer 
    return ans; 
  
# Driver Code 
if __name__ == "__main__" : 
  
    # Given array arr[] 
    arr = [ 5, 1, 3, 4, 5, 6 ]; 
  
    N = len(arr); 
  
    # Function call 
    print(sumOfElements(arr, N)); 
  
# This code is contributed by AnkitRai01


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Kadane's Algorithm to find 
// the maximum sum sub array 
static int kadane(List v)
{
    int maxSoFar = 0;
    int maxEndingHere = 0;
  
    // Iterate array v
    for(int i = 0; i < v.Count; i++) 
    {
        maxEndingHere += v[i];
              
        // Update the maximum
        maxSoFar = Math.Max(maxEndingHere,
                            maxSoFar);
              
        // Update maxEndingHere to 0 if it
        // is less than 0
        maxEndingHere = Math.Max(maxEndingHere, 0);
    }
      
    // Return maximum sum
    return maxSoFar;
}
  
// Function to find the sum
// of even indexed elements
// after modification in array.
static int sumOfElements(int []arr, int n)
{
    int sum = 0;
  
    // Find initial sum of
    // even indexed elements
    for(int i = 0; i < n; i++)
    {
        if (i % 2 == 0)
            sum += arr[i];
    }
  
    // Create two vectors to store
    // the consecutive differences
    // of elements
    List v1 = new List();
    List v2 = new List();
  
    for(int i = 1; i < n; i += 2) 
    {
        v1.Add(arr[i] - arr[i - 1]);
          
        if (i + 1 < n)
        {
            v2.Add(arr[i] - arr[i + 1]);
        }
    }
      
    // Find the maximum sum subarray
    int option1 = kadane(v1);
    int option2 = kadane(v2);
  
    // Add the maximum value
    // to initial sum
    int ans = sum + Math.Max(option1,
                             option2);
  
    // Return the answer
    return ans;
}
  
// Driver Code
public static void Main(String[] args)
{
      
    // Given array []arr
    int []arr = { 5, 1, 3, 4, 5, 6 };
  
    int N = arr.Length;
  
    // Function call
    Console.Write(sumOfElements(arr, N));
}
}
  
// This code is contributed by Amit Katiyar


输出:
15

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