Maximum sum subarray of even length
Last Updated :
12 Jul, 2025
Given an array arr[] of N elements, the task is to find the maximum sum of any subarray of length X such that X > 0 and X % 2 = 0.
Examples:
Input: arr[] = {1, 2, 3}
Output: 5
{2, 3} is the required subarray.
Input: arr[] = {8, 9, -8, 9, 10}
Output: 20
{9, -8, 9, 10} is the required subarray.
Even though {8, 9, -8, 9, 10} has the maximum sum
but it is not of even length.
Approach: This problem is a variation of maximum subarray sum problem and can be solved using dynamic programming approach. Create an array dp[] where dp[i] will store the maximum sum of an even length subarray whose first element is arr[i]. Now the recurrence relation will be:
dp[i] = max((arr[i] + arr[i + 1]), (arr[i] + arr[i + 1] + dp[i + 2]))
This is because the maximum sum even length subarray starting with the element arr[i] can either be the sum of arr[i] and arr[i + 1] or it can be arr[i] + arr[i + 1] added with the maximum sum of even length subarray starting with arr[i + 2] i.e. dp[i + 2]. Take the maximum of these two.
In the end, the maximum value from the dp[] array will be the required answer.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the maximum
// subarray sum of even length
int maxEvenLenSum(int arr[], int n)
{
// There has to be at
// least 2 elements
if (n < 2)
return 0;
// dp[i] will store the maximum
// subarray sum of even length
// starting at arr[i]
int dp[n] = { 0 };
// Valid subarray cannot start from
// the last element as its
// length has to be even
dp[n - 1] = 0;
dp[n - 2] = arr[n - 2] + arr[n - 1];
for (int i = n - 3; i >= 0; i--) {
// arr[i] and arr[i + 1] can be added
// to get an even length subarray
// starting at arr[i]
dp[i] = arr[i] + arr[i + 1];
// If the sum of the valid subarray starting
// from arr[i + 2] is greater than 0 then it
// can be added with arr[i] and arr[i + 1]
// to maximize the sum of the subarray
// starting from arr[i]
if (dp[i + 2] > 0)
dp[i] += dp[i + 2];
}
// Get the sum of the even length
// subarray with maximum sum
int maxSum = *max_element(dp, dp + n);
return maxSum;
}
// Driver code
int main()
{
int arr[] = { 8, 9, -8, 9, 10 };
int n = sizeof(arr) / sizeof(int);
cout << maxEvenLenSum(arr, n);
return 0;
}
Java
// Java implementation of the approach
import java.util.Arrays;
class GFG
{
// Function to return the maximum
// subarray sum of even length
static int maxEvenLenSum(int arr[], int n)
{
// There has to be at
// least 2 elements
if (n < 2)
return 0;
// dp[i] will store the maximum
// subarray sum of even length
// starting at arr[i]
int []dp = new int[n];
// Valid subarray cannot start from
// the last element as its
// length has to be even
dp[n - 1] = 0;
dp[n - 2] = arr[n - 2] + arr[n - 1];
for (int i = n - 3; i >= 0; i--)
{
// arr[i] and arr[i + 1] can be added
// to get an even length subarray
// starting at arr[i]
dp[i] = arr[i] + arr[i + 1];
// If the sum of the valid subarray starting
// from arr[i + 2] is greater than 0 then it
// can be added with arr[i] and arr[i + 1]
// to maximize the sum of the subarray
// starting from arr[i]
if (dp[i + 2] > 0)
dp[i] += dp[i + 2];
}
// Get the sum of the even length
// subarray with maximum sum
int maxSum = Arrays.stream(dp).max().getAsInt();
return maxSum;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 8, 9, -8, 9, 10 };
int n = arr.length;
System.out.println(maxEvenLenSum(arr, n));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach
# Function to return the maximum
# subarray sum of even length
def maxEvenLenSum(arr, n):
# There has to be at
# least 2 elements
if (n < 2):
return 0
# dp[i] will store the maximum
# subarray sum of even length
# starting at arr[i]
dp = [0 for i in range(n)]
# Valid subarray cannot start from
# the last element as its
# length has to be even
dp[n - 1] = 0
dp[n - 2] = arr[n - 2] + arr[n - 1]
for i in range(n - 3, -1, -1):
# arr[i] and arr[i + 1] can be added
# to get an even length subarray
# starting at arr[i]
dp[i] = arr[i] + arr[i + 1]
# If the sum of the valid subarray
# starting from arr[i + 2] is
# greater than 0 then it can be added
# with arr[i] and arr[i + 1]
# to maximize the sum of the
# subarray starting from arr[i]
if (dp[i + 2] > 0):
dp[i] += dp[i + 2]
# Get the sum of the even length
# subarray with maximum sum
maxSum = max(dp)
return maxSum
# Driver code
arr = [8, 9, -8, 9, 10]
n = len(arr)
print(maxEvenLenSum(arr, n))
# This code is contributed by Mohit Kumar
C#
// C# implementation of the approach
using System;
class GFG
{
static int MaxSum(int []arr)
{
// assigning first element to the array
int large = arr[0];
// loop to compare value of large
// with other elements
for (int i = 1; i < arr.Length; i++)
{
// if large is smaller than other element
// assign that element to the large
if (large < arr[i])
large = arr[i];
}
return large;
}
// Function to return the maximum
// subarray sum of even length
static int maxEvenLenSum(int []arr, int n)
{
// There has to be at
// least 2 elements
if (n < 2)
return 0;
// dp[i] will store the maximum
// subarray sum of even length
// starting at arr[i]
int []dp = new int[n];
// Valid subarray cannot start from
// the last element as its
// length has to be even
dp[n - 1] = 0;
dp[n - 2] = arr[n - 2] + arr[n - 1];
for (int i = n - 3; i >= 0; i--)
{
// arr[i] and arr[i + 1] can be added
// to get an even length subarray
// starting at arr[i]
dp[i] = arr[i] + arr[i + 1];
// If the sum of the valid subarray starting
// from arr[i + 2] is greater than 0 then it
// can be added with arr[i] and arr[i + 1]
// to maximize the sum of the subarray
// starting from arr[i]
if (dp[i + 2] > 0)
dp[i] += dp[i + 2];
}
// Get the sum of the even length
// subarray with maximum sum
int maxSum = MaxSum(dp);
return maxSum;
}
// Driver code
public static void Main()
{
int []arr = { 8, 9, -8, 9, 10 };
int n = arr.Length;
Console.WriteLine(maxEvenLenSum(arr, n));
}
}
// This code is contributed by kanugargng
JavaScript
<script>
// Javascript implementation of the approach
// Function to return the maximum
// subarray sum of even length
function maxEvenLenSum(arr, n) {
// There has to be at
// least 2 elements
if (n < 2)
return 0;
// dp[i] will store the maximum
// subarray sum of even length
// starting at arr[i]
let dp = new Array(n).fill(0);
// Valid subarray cannot start from
// the last element as its
// length has to be even
dp[n - 1] = 0;
dp[n - 2] = arr[n - 2] + arr[n - 1];
for (let i = n - 3; i >= 0; i--) {
// arr[i] and arr[i + 1] can be added
// to get an even length subarray
// starting at arr[i]
dp[i] = arr[i] + arr[i + 1];
// If the sum of the valid subarray starting
// from arr[i + 2] is greater than 0 then it
// can be added with arr[i] and arr[i + 1]
// to maximize the sum of the subarray
// starting from arr[i]
if (dp[i + 2] > 0)
dp[i] += dp[i + 2];
}
// Get the sum of the even length
// subarray with maximum sum
let maxSum = dp.sort((a, b) => b - a)[0];
return maxSum;
}
// Driver code
let arr = [8, 9, -8, 9, 10];
let n = arr.length;
document.write(maxEvenLenSum(arr, n));
// This code is contributed by _saurabh_jaiswal.
</script>
Time complexity: O(n)
Space complexity: O(n)
Efficient approach : Space optimization O(1)
To optimize the space complexity of previous approach we using only two variables to keep track of the previous two subproblems instead of creating an array of size n to store all the subproblem solutions. This way, we can reduce the space complexity from O(n) to O(1).
Implementation Steps:
- Check if the array size is less than 2, return 0 if true.
- Initialize prevPrevSum to 0 and prevSum to arr[n-2] + arr[n-1], which represents the sum of the last two elements of the array.
- Traverse the array from the second-last index to the first index and compute the sum of every even length subarray that ends at the current index.
- Add the current element and the next element of the array to get the sum of the current even-length subarray.
- If the sum of the subarray two indices ahead is greater than 0, add it to the current subarray sum.
- Update prevPrevSum and prevSum with the previous subarray sums for further iterations.
- At last Return the maximum of prevSum and prevPrevSum.
Implementation:
C++
// C++ code for above approach
#include <bits/stdc++.h>
using namespace std;
int maxEvenLenSum(int arr[], int n)
{
// There has to be at
// least 2 elements
if (n < 2)
return 0;
// initialize variables to store the previous values
int prevPrevSum = 0, prevSum = arr[n - 2] + arr[n - 1], currSum;
// iterate over subproblems and get the current value from previous computations
for (int i = n - 3; i >= 0; i--) {
currSum = arr[i] + arr[i + 1];
if (prevPrevSum > 0)
currSum += prevPrevSum;
// assigning values for further iterations
prevPrevSum = prevSum;
prevSum = currSum;
}
// return answer
return max(prevSum, prevPrevSum);
}
// Driver code
int main()
{
int arr[] = { 8, 9, -8, 9, 10 };
int n = sizeof(arr) / sizeof(int);
// function call
cout << maxEvenLenSum(arr, n);
return 0;
}
Java
// Java code for above approach
import java.util.*;
public class Main {
static int maxEvenLenSum(int arr[], int n) {
// There has to be at
// least 2 elements
if (n < 2)
return 0;
// initialize variables to store the previous values
int prevPrevSum = 0, prevSum = arr[n - 2] + arr[n - 1], currSum;
// iterate over subproblems and get the current value from previous computations
for (int i = n - 3; i >= 0; i--) {
currSum = arr[i] + arr[i + 1];
if (prevPrevSum > 0)
currSum += prevPrevSum;
// assigning values for further iterations
prevPrevSum = prevSum;
prevSum = currSum;
}
// return answer
return Math.max(prevSum, prevPrevSum);
}
// Driver code
public static void main(String[] args) {
int arr[] = { 8, 9, -8, 9, 10 };
int n = arr.length;
// function call
System.out.println(maxEvenLenSum(arr, n));
}
}
Python3
def maxEvenLenSum(arr, n):
# There has to be at least 2 elements
if n < 2:
return 0
# initialize variables to store the previous values
prevPrevSum = 0
prevSum = arr[n - 2] + arr[n - 1]
# iterate over subproblems and get the current value from previous computations
for i in range(n - 3, -1, -1):
currSum = arr[i] + arr[i + 1]
if prevPrevSum > 0:
currSum += prevPrevSum
# assigning values for further iterations
prevPrevSum = prevSum
prevSum = currSum
# return answer
return max(prevSum, prevPrevSum)
# Driver code
arr = [8, 9, -8, 9, 10]
n = len(arr)
# function call
print(maxEvenLenSum(arr, n))
C#
using System;
class GFG {
static int maxEvenLenSum(int[] arr, int n)
{
// There has to be at least 2 elements
if (n < 2)
return 0;
// initialize variables to store the previous values
int prevPrevSum = 0,
prevSum = arr[n - 2] + arr[n - 1], currSum;
// iterate over subproblems and get the current
// value from previous computations
for (int i = n - 3; i >= 0; i--) {
currSum = arr[i] + arr[i + 1];
if (prevPrevSum > 0)
currSum += prevPrevSum;
// assigning values for further iterations
prevPrevSum = prevSum;
prevSum = currSum;
}
// return answer
return Math.Max(prevSum, prevPrevSum);
}
// Driver code
static void Main()
{
int[] arr = { 8, 9, -8, 9, 10 };
int n = arr.Length;
// function call
Console.Write(maxEvenLenSum(arr, n));
}
}
JavaScript
<script>
// Javascript code for above approach
function maxEvenLenSum(arr, n) {
// There has to be at
// least 2 elements
if (n < 2) {
return 0;
}
// Initialize variables to store the previous values
let prevPrevSum = 0;
let prevSum = arr[n - 2] + arr[n - 1];
let currSum;
// Iterate over subproblems and get the current value from previous computations
for (let i = n - 3; i >= 0; i--) {
currSum = arr[i] + arr[i + 1];
if (prevPrevSum > 0) {
currSum += prevPrevSum;
}
// Assign values for further iterations
prevPrevSum = prevSum;
prevSum = currSum;
}
// Return answer
return Math.max(prevSum, prevPrevSum);
}
// Driver code
const arr = [8, 9, -8, 9, 10];
const n = arr.length;
// Function call
document.write(maxEvenLenSum(arr, n));
// This code is contributed by Vaibhav Nandan
</script>
Output
20
Time complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem