Maximum Sum Alternating Subarray
Last Updated :
18 Nov, 2021
Given an array arr[] of size N, the task is to find the maximum alternating sum of a subarray possible for a given array.
Alternating Subarray Sum: Considering a subarray {arr[i], arr[j]}, alternating sum of the subarray is arr[i] - arr[i + 1] + arr[i + 2] - ........ (+ / -) arr[j].
Examples:
Input: arr[] = {-4, -10, 3, 5}
Output: 9
Explanation: Subarray {arr[0], arr[2]} = {-4, -10, 3}. Therefore, the sum of this subarray is 9.
Input: arr[] = {-1, 2, -1, 4, 7}
Output: 7
Approach: The given problem can be solved by using Dynamic Programming. Follow the steps below to solve the problem:
- Initialize a variable, say sum as 0, which will hold a maximum alternating subarray sum and a variable, say sumSoFar, to store the sum of subarrays starting from even indices in the 1st loop and the sum starting from odd indices, in the 2nd loop.
- In every iteration of both the loops, update sum as max(sum, sumSoFar).
- Finally, return the maximum alternating sum stored in the sum variable.
Below is the implementation of the above approach:
C++
// C++ implementation for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum alternating
// sum of a subarray for the given array
int alternatingSum(int arr[],int n)
{
int sum = 0;
int sumSoFar = 0;
// Traverse the array
for (int i = 0; i < n; i++) {
// Store sum of subarrays
// starting at even indices
if (i % 2 == 1) {
sumSoFar -= arr[i];
}
else {
sumSoFar = max(
sumSoFar + arr[i], arr[i]);
}
// Update sum
sum = max(sum, sumSoFar);
}
sumSoFar = 0;
// Traverse the array
for (int i = 1; i < n; i++) {
// Store sum of subarrays
// starting at odd indices
if (i % 2 == 0) {
sumSoFar -= arr[i];
}
else {
sumSoFar = max(
sumSoFar + arr[i], arr[i]);
}
// Update sum
sum = max(sum, sumSoFar);
}
return sum;
}
// Driver code
int main()
{
// Given Input
int arr[] ={ -4, -10, 3, 5 };
int n = sizeof(arr)/sizeof(arr[0]);
// Function call
int ans = alternatingSum(arr,n);
cout<<ans<<endl;
return 0;
}
// This code is contributed by Potta Lokesh
Java
// Java implementation for the above approach
import java.io.*;
class GFG {
// Function to find the maximum alternating
// sum of a subarray for the given array
public static int alternatingSum(int[] arr)
{
int sum = 0;
int sumSoFar = 0;
// Traverse the array
for (int i = 0; i < arr.length; i++) {
// Store sum of subarrays
// starting at even indices
if (i % 2 == 1) {
sumSoFar -= arr[i];
}
else {
sumSoFar = Math.max(
sumSoFar + arr[i], arr[i]);
}
// Update sum
sum = Math.max(sum, sumSoFar);
}
sumSoFar = 0;
// Traverse the array
for (int i = 1; i < arr.length; i++) {
// Store sum of subarrays
// starting at odd indices
if (i % 2 == 0) {
sumSoFar -= arr[i];
}
else {
sumSoFar = Math.max(
sumSoFar + arr[i], arr[i]);
}
// Update sum
sum = Math.max(sum, sumSoFar);
}
return sum;
}
// Driver code
public static void main(String[] args)
{
// Given Input
int arr[] = new int[] { -4, -10, 3, 5 };
// Function call
int ans = alternatingSum(arr);
System.out.println(ans);
}
}
Python3
# Python implementation for the above approach
# Function to find the maximum alternating
# sum of a subarray for the given array
def alternatingSum(arr, n):
sum_ = 0
sumSoFar = 0
# Traverse the array
for i in range(n):
# Store sum of subarrays
# starting at even indices
if i % 2 == 1:
sumSoFar -= arr[i]
else:
sumSoFar = max(arr[i], sumSoFar + arr[i])
# Update sum
sum_ = max(sum_, sumSoFar)
sumSoFar = 0
# Traverse array
for i in range(1, n):
# Store sum of subarrays
# starting at odd indices
if i % 2 == 0:
sumSoFar -= arr[i]
else:
sumSoFar = max(arr[i], sumSoFar + arr[i])
sum_ = max(sum_, sumSoFar)
# update sum
return sum_
# given array
arr = [-4, -10, 3, 5]
n = len(arr)
# return sum
ans = alternatingSum(arr, n)
print(ans)
# This code is contributed by Parth Manchanda
C#
// C# implementation for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find the maximum alternating
// sum of a subarray for the given array
static int alternatingSum(int []arr,int n)
{
int sum = 0;
int sumSoFar = 0;
// Traverse the array
for(int i = 0; i < n; i++)
{
// Store sum of subarrays
// starting at even indices
if (i % 2 == 1)
{
sumSoFar -= arr[i];
}
else
{
sumSoFar = Math.Max(
sumSoFar + arr[i], arr[i]);
}
// Update sum
sum = Math.Max(sum, sumSoFar);
}
sumSoFar = 0;
// Traverse the array
for(int i = 1; i < n; i++)
{
// Store sum of subarrays
// starting at odd indices
if (i % 2 == 0)
{
sumSoFar -= arr[i];
}
else
{
sumSoFar = Math.Max(
sumSoFar + arr[i], arr[i]);
}
// Update sum
sum = Math.Max(sum, sumSoFar);
}
return sum;
}
// Driver code
public static void Main()
{
// Given Input
int []arr = { -4, -10, 3, 5 };
int n = arr.Length;
// Function call
int ans = alternatingSum(arr,n);
Console.Write(ans);
}
}
// This code is contributed by SURENDRA_GANGWAR
JavaScript
<script>
// JavaScript implementation for the above approach
// Function to find the maximum alternating
// sum of a subarray for the given array
function alternatingSum(arr)
{
var sum = 0;
var sumSoFar = 0;
// Traverse the array
for (var i = 0; i < arr.length; i++) {
// Store sum of subarrays
// starting at even indices
if (i % 2 == 1) {
sumSoFar -= arr[i];
}
else {
sumSoFar = Math.max(
sumSoFar + arr[i], arr[i]);
}
// Update sum
sum = Math.max(sum, sumSoFar);
}
sumSoFar = 0;
// Traverse the array
for (var i = 1; i < arr.length; i++) {
// Store sum of subarrays
// starting at odd indices
if (i % 2 == 0) {
sumSoFar -= arr[i];
}
else {
sumSoFar = Math.max(
sumSoFar + arr[i], arr[i]);
}
// Update sum
sum = Math.max(sum, sumSoFar);
}
return sum;
}
// Driver code
// Given Input
var arr = new Array ( -4, -10, 3, 5 );
// Function call
var ans = alternatingSum(arr);
document.write(ans);
// This code is contributed by shivanisinghss2110
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Maximum sum alternating subsequence Given an array, the task is to find sum of maximum sum alternating subsequence starting with first element. Here alternating sequence means first decreasing, then increasing, then decreasing, ... For example 10, 5, 14, 3 is an alternating sequence. Note that the reverse type of sequence (increasing
13 min read
Maximum Subarray Sum of Alternate Parity Given array A[] of size N. The Task for this problem is to find the maximum subarray (Subarrays are arrays within another array. Subarrays contain contiguous elements) sum such that adjacent elements of the subarray should have different parity. Examples: Input: A[] = {-1, 4, -1, 0, 5, -4} Output: 8
7 min read
Maximum sum bitonic subarray Given an array containing n numbers. The problem is to find the maximum sum bitonic subarray. A bitonic subarray is a subarray in which elements are first increasing and then decreasing. A strictly increasing or strictly decreasing subarray is also considered a bitonic subarray. Time Complexity of O
15+ min read
Maximum sum subarray after altering the array Given an array arr[] of size N. The task is to find the maximum subarray sum possible after performing the given operation at most once. In a single operation, you can choose any index i and either the subarray arr[0...i] or the subarray arr[i...N-1] can be reversed. Examples: Input: arr[] = {3, 4,
15+ min read
Longest subarray having maximum sum Given an array arr[] containing n integers. The problem is to find the length of the subarray having maximum sum. If there exists two or more subarrays with maximum sum then print the length of the longest subarray.Examples: Input : arr[] = {5, -2, -1, 3, -4}Output : 4There are two subarrays with ma
12 min read