📌  相关文章
📜  从给定数组中找到最大交替子序列总和

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

给定一个大小为 n 的数组 arr[]具有正整数和负整数(不包括零)。找到给定序列的最大尺寸交替子序列的最大总和,即,在每个相邻元素的子序列符号相反,例如,如果第一个为正,则第二个必须为负,后跟另一个正整数,依此类推.

例子:

幼稚的方法:
解决上述问题的简单方法是找到所有交替子序列及其和,并返回所有子序列中的最大和。

有效的方法:
解决上述问题的有效方法是每次在连续的正和连续的负元素中挑选最大的元素,并将其添加到迄今为止的最大和中。存储最大总和的变量将保存最终答案。

下面是上述方法的实现:

C++14
// C++ program to find the maximum
// alternating subsequence sum for
// a given array
#include 
using namespace std;
 
// Function to find maximum
// alternating subequence sum
int maxAlternatingSum(int arr[], int n)
{
     
    // Initialize sum to 0
    int max_sum = 0;
    int i = 0;
      
    while (i < n)
    {
        int current_max = arr[i];
        int k = i;
          
         while (k < n &&
              ((arr[i] > 0 && arr[k] > 0) ||
               (arr[i] < 0 && arr[k] < 0)))
        {
            current_max = max(current_max, arr[k]);
            k += 1;
        }
          
        // Calculate the sum
        max_sum += current_max;
          
        i = k;
    }
      
    // Return the final result
    return max_sum;   
}
 
// Driver Code
int main()
{
     
    // Array initialization
    int arr[] = { 1, 2, 3, 4, -1, -2 };
      
    // Length of array
    int n = sizeof(arr) / sizeof(arr[0]);
     
    cout << maxAlternatingSum(arr, n);
    return 0;
}
 
// This code is contributed by avanitrachhadiya2155


Java
// Java program to find the maximum
// alternating subsequence sum for
// a given array
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to find maximum
// alternating subequence sum
static int maxAlternatingSum(int[] arr, int n)
{
     
    // Initialize sum to 0
    int max_sum = 0;
     
    int i = 0;
     
    while (i < n)
    {
        int current_max = arr[i];
        int k = i;
         
         while (k < n &&
              ((arr[i] > 0 && arr[k] > 0) ||
               (arr[i] < 0 && arr[k] < 0)))
         {
            current_max = Math.max(current_max, arr[k]);
            k += 1;
        }
         
        // Calculate the sum
        max_sum += current_max;
         
        i = k;
    }
     
    // Return the final result
    return max_sum;
}
 
// Driver Code
public static void main(String args[])
{
     
    // Array initialization
    int[] arr = { 1, 2, 3, 4, -1, -2 };
     
    // Length of array
    int n = arr.length;
     
    System.out.println(maxAlternatingSum(arr, n));
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program to find the maximum alternating
# subsequence sum for a given array
 
# Function to find maximum
# alternating subequence sum
def maxAlternatingSum(arr, n):
 
    # initialize sum to 0
    max_sum = 0
     
    i = 0
     
    while i0 and arr[k]>0)
        or (arr[i]<0 and arr[k]<0)):
             
            current_max = max(current_max, arr[k])
             
            k+= 1
         
        # calculate the sum
        max_sum+= current_max
         
        i = k
         
    # return the final result
    return max_sum
 
 
# Driver code
 
# array initiaisation
arr = [1, 2, 3, 4, -1, -2]
 
# length of array
n = len(arr)
 
print(maxAlternatingSum(arr, n))


C#
// C# program to find the maximum
// alternating subsequence sum for
// a given array
using System;
class GFG{
 
// Function to find maximum
// alternating subequence sum
static int maxAlternatingSum(int[] arr,
                             int n)
{
  // Initialize sum to 0
  int max_sum = 0;
 
  int i = 0;
 
  while (i < n)
  {
    int current_max = arr[i];
    int k = i;
 
    while (k < n &&
          ((arr[i] > 0 && arr[k] > 0) ||
           (arr[i] < 0 && arr[k] < 0)))
    {
      current_max = Math.Max(current_max,
                             arr[k]);
      k += 1;
    }
 
    // Calculate the sum
    max_sum += current_max;
 
    i = k;
  }
 
  // Return the final result
  return max_sum;
}
 
// Driver Code
public static void Main()
{    
  // Array initialization
  int[] arr = {1, 2, 3, 4,
               -1, -2};
 
  // Length of array
  int n = arr.Length;
 
  Console.Write(maxAlternatingSum(arr, n));
}
}
 
// This code is contributed by Chitranayal


Javascript


输出:
3

时间复杂度: O(n)