Reverse a subarray of the given array to minimize the sum of elements at even position
Last Updated :
15 Jul, 2025
Given an array arr[] of positive integers. The task is to reverse a subarray to minimize the sum of elements at even places and print the minimum sum.
Note: Perform the move only one time. Subarray might not be reversed.
Example:
Input: arr[] = {1, 2, 3, 4, 5}
Output: 7
Explanation:
Sum of elements at even positions initially = arr[0] + arr[2] + arr[4] = 1 + 3 + 5 = 9
On reversing the subarray from position [1, 4], the array becomes: {1, 5, 4, 3, 2}
Now the sum of elements at even positions = arr[0] + arr[2] + arr[4] = 1 + 4 + 2 = 7, which is the minimum sum.
Input: arr[] = {0, 1, 4, 3}
Output: 1
Explanation:
Sum of elements at even positions initially = arr[0] + arr[2] = 0 + 4 = 4
On reversing the subarray from position [1, 2], the array becomes: {0, 4, 1, 3}
Now the sum of elements at even positions = arr[0] + arr[2] = 0 + 1 = 1, which is the minimum sum.
Naive Approach: The idea is to apply the Brute Force method and generate all the subarrays and check the sum of elements at the even position. Print the sum which is the minimum among all.
Below is the code for the above approach :
C++
// C++ implementation to reverse a subarray
// of the given array to minimize the
// sum of elements at even position
#include <bits/stdc++.h>
#define N 5
using namespace std;
// Function that will give
// the max negative value
int after_rev(vector<int> v)
{
int mini = 0, count = 0;
for (int i = 0; i < v.size(); i++) {
count += v[i];
// Check for count
// greater than 0
// as we require only
// negative solution
if (count > 0)
count = 0;
if (mini > count)
mini = count;
}
return mini;
}
// Function to print the minimum sum
void print(int arr[N])
{
int sum = 0;
// Taking sum of only
// even index elements
for (int i = 0; i < N; i += 2)
sum += arr[i];
// Naive approach to generate all subarrays
// and check their sums at even positions
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
// Reverse the subarray from i to j
reverse(arr + i, arr + j + 1);
// Update the sum if the current subarray
// gives a smaller sum at even positions
int current_sum = 0;
for (int k = 0; k < N; k += 2)
current_sum += arr[k];
sum = min(sum, current_sum);
// Reverse the subarray back to original
reverse(arr + i, arr + j + 1);
}
}
cout << sum << endl;
}
// Driver code
int main()
{
int arr[N] = { 0, 1, 4, 3 };
print(arr);
return 0;
}
Java
import java.util.Arrays;
public class Main {
static int afterRev(int[] arr) {
int mini = 0, count = 0;
for (int i = 0; i < arr.length; i++) {
count += arr[i];
// Check for count greater than 0
// as we require only negative solution
if (count > 0)
count = 0;
if (mini > count)
mini = count;
}
return mini;
}
static void print(int[] arr) {
int sum = 0;
// Taking sum of only even index elements
for (int i = 0; i < arr.length; i += 2)
sum += arr[i];
// Naive approach to generate all subarrays
// and check their sums at even positions
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length; j++) {
// Reverse the subarray from i to j
reverse(arr, i, j);
// Update the sum if the current subarray
// gives a smaller sum at even positions
int currentSum = 0;
for (int k = 0; k < arr.length; k += 2)
currentSum += arr[k];
sum = Math.min(sum, currentSum);
// Reverse the subarray back to original
reverse(arr, i, j);
}
}
System.out.println(sum);
}
static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
int[] arr = { 0, 1, 4, 3 };
print(arr);
}
}
Python3
# Function that will give the max negative value
def after_rev(v):
mini = 0
count = 0
for i in range(len(v)):
count += v[i]
# Check for count greater than 0
# as we require only negative solution
if count > 0:
count = 0
if mini > count:
mini = count
return mini
# Function to print the minimum sum
def print_sum(arr):
sum_val = 0
# Taking sum of only even index elements
for i in range(0, len(arr), 2):
sum_val += arr[i]
# Naive approach to generate all subarrays
# and check their sums at even positions
for i in range(len(arr)):
for j in range(i, len(arr)):
# Reverse the subarray from i to j
arr[i:j+1] = arr[i:j+1][::-1]
# Update the sum if the current subarray
# gives a smaller sum at even positions
current_sum = 0
for k in range(0, len(arr), 2):
current_sum += arr[k]
sum_val = min(sum_val, current_sum)
# Reverse the subarray back to the original
arr[i:j+1] = arr[i:j+1][::-1]
print(sum_val)
# Driver code
if __name__ == "__main__":
arr = [0, 1, 4, 3]
print_sum(arr)
C#
using System;
class Program
{
static int AfterRev(int[] arr)
{
int mini = 0, count = 0;
for (int i = 0; i < arr.Length; i++)
{
count += arr[i];
// Check for count
// greater than 0
// as we require only
// negative solution
if (count > 0)
count = 0;
if (mini > count)
mini = count;
}
return mini;
}
static void Print(int[] arr)
{
int sum = 0;
// Taking sum of only
// even index elements
for (int i = 0; i < arr.Length; i += 2)
sum += arr[i];
// Naive approach to generate all subarrays
// and check their sums at even positions
for (int i = 0; i < arr.Length; i++)
{
for (int j = i; j < arr.Length; j++)
{
// Reverse the subarray from i to j
Array.Reverse(arr, i, j - i + 1);
// Update the sum if the current subarray
// gives a smaller sum at even positions
int currentSum = 0;
for (int k = 0; k < arr.Length; k += 2)
currentSum += arr[k];
sum = Math.Min(sum, currentSum);
// Reverse the subarray back to original
Array.Reverse(arr, i, j - i + 1);
}
}
Console.WriteLine(sum);
}
static void Main(string[] args)
{
int[] arr = { 0, 1, 4, 3 };
Print(arr);
}
}
JavaScript
function afterRev(arr) {
let mini = 0;
let count = 0;
for (let i = 0; i < arr.length; i++) {
count += arr[i];
// Check for count
// greater than 0
// as we require only
// negative solution
if (count > 0)
count = 0;
if (mini > count)
mini = count;
}
return mini;
}
function print(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i += 2)
sum += arr[i];
let originalArr = [...arr]; // Create a copy of the original array
for (let i = 0; i < arr.length; i++) {
for (let j = i; j < arr.length; j++) {
// Reverse the subarray from i to j
arr = reverseSubarray(arr, i, j);
let currentSum = 0;
for (let k = 0; k < arr.length; k += 2)
currentSum += arr[k];
sum = Math.min(sum, currentSum);
// Restore the original subarray
arr = originalArr.slice();
}
}
console.log(sum);
}
function reverseSubarray(arr, start, end) {
let subarray = arr.slice(start, end + 1);
subarray.reverse();
for (let i = start, j = 0; i <= end; i++, j++) {
arr[i] = subarray[j];
}
return arr;
}
const arr = [0, 1, 4, 3];
print(arr);
Time Complexity: O(N3)
Auxiliary Space: O(N)
Efficient Approach: The idea is to observe the following important points for array arr[]:
- Reversing the subarray of odd length won't change the sum because all elements at even index will again come to the even index.
- Reversing an even length subarray will make all elements at index position come to the even index and elements at even index goes to the odd index.
- Sum of elements will change only when an odd index element is put at even indexed elements. Let's say element at index 1 can go to index 0 or index 2.
- On reversing from an even index to another even index example from index 2 to 4, it will be covering in the first case or if from odd index to even index example from index 1 to 4, it will be covering the second case.
Below are the steps of the approach based on the above observations:
- So the idea is to find the sum of only even index elements and initialize two arrays lets say v1 and v2 such that v1 will keep account of change if first index element goes to 0 whereas v2 will keep the account of change if first index element goes to 2.
- Get the minimum of the two values and check if it's lesser than 0. If it is, then add it to the answer and finally return the answer.
Below is the implementation of the above approach :
C++
// C++ implementation to reverse a subarray
// of the given array to minimize the
// sum of elements at even position
#include <bits/stdc++.h>
#define N 5
using namespace std;
// Function that will give
// the max negative value
int after_rev(vector<int> v)
{
int mini = 0, count = 0;
for (int i = 0; i < v.size(); i++) {
count += v[i];
// Check for count
// greater than 0
// as we require only
// negative solution
if (count > 0)
count = 0;
if (mini > count)
mini = count;
}
return mini;
}
// Function to print the minimum sum
void print(int arr[N])
{
int sum = 0;
// Taking sum of only
// even index elements
for (int i = 0; i < N; i += 2)
sum += arr[i];
// Initialize two vectors v1, v2
vector<int> v1, v2;
// v1 will keep account for change
// if 1th index element goes to 0
for (int i = 0; i + 1 < N; i += 2)
v1.push_back(arr[i + 1] - arr[i]);
// v2 will keep account for change
// if 1th index element goes to 2
for (int i = 1; i + 1 < N; i += 2)
v2.push_back(arr[i] - arr[i + 1]);
// Get the max negative value
int change = min(after_rev(v1),
after_rev(v2));
if (change < 0)
sum += change;
cout << sum << endl;
}
// Driver code
int main()
{
int arr[N] = { 0, 1, 4, 3 };
print(arr);
return 0;
}
Java
// Java implementation to reverse a subarray
// of the given array to minimize the
// sum of elements at even position
import java.util.*;
class GFG{
static final int N = 5;
// Function that will give
// the max negative value
static int after_rev(Vector<Integer> v)
{
int mini = 0, count = 0;
for(int i = 0; i < v.size(); i++)
{
count += v.get(i);
// Check for count greater
// than 0 as we require only
// negative solution
if (count > 0)
count = 0;
if (mini > count)
mini = count;
}
return mini;
}
// Function to print the minimum sum
static void print(int arr[])
{
int sum = 0;
// Taking sum of only
// even index elements
for(int i = 0; i < N; i += 2)
sum += arr[i];
// Initialize two vectors v1, v2
Vector<Integer> v1, v2;
v1 = new Vector<Integer>();
v2 = new Vector<Integer>();
// v1 will keep account for change
// if 1th index element goes to 0
for(int i = 0; i + 1 < N; i += 2)
v1.add(arr[i + 1] - arr[i]);
// v2 will keep account for change
// if 1th index element goes to 2
for(int i = 1; i + 1 < N; i += 2)
v2.add(arr[i] - arr[i + 1]);
// Get the max negative value
int change = Math.min(after_rev(v1),
after_rev(v2));
if (change < 0)
sum += change;
System.out.print(sum + "\n");
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 0, 1, 4, 3, 0 };
print(arr);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation to reverse
# a subarray of the given array to
# minimize the sum of elements at
# even position
# Function that will give
# the max negative value
def after_rev(v):
mini = 0
count = 0
for i in range(len(v)):
count += v[i]
# Check for count greater
# than 0 as we require only
# negative solution
if(count > 0):
count = 0
if(mini > count):
mini = count
return mini
# Function to print the
# minimum sum
def print_f(arr):
sum = 0
# Taking sum of only
# even index elements
for i in range(0, len(arr), 2):
sum += arr[i]
# Initialize two vectors v1, v2
v1, v2 = [], []
# v1 will keep account for change
# if 1th index element goes to 0
i = 1
while i + 1 < len(arr):
v1.append(arr[i + 1] - arr[i])
i += 2
# v2 will keep account for change
# if 1th index element goes to 2
i = 1
while i + 1 < len(arr):
v2.append(arr[i] - arr[i + 1])
i += 2
# Get the max negative value
change = min(after_rev(v1),
after_rev(v2))
if(change < 0):
sum += change
print(sum)
# Driver code
if __name__ == '__main__':
arr = [ 0, 1, 4, 3 ]
print_f(arr)
# This code is contributed by Shivam Singh
C#
// C# implementation to reverse a subarray
// of the given array to minimize the
// sum of elements at even position
using System;
using System.Collections.Generic;
class GFG{
static readonly int N = 5;
// Function that will give
// the max negative value
static int after_rev(List<int> v)
{
int mini = 0, count = 0;
for(int i = 0; i < v.Count; i++)
{
count += v[i];
// Check for count greater
// than 0 as we require only
// negative solution
if (count > 0)
count = 0;
if (mini > count)
mini = count;
}
return mini;
}
// Function to print the minimum sum
static void print(int []arr)
{
int sum = 0;
// Taking sum of only
// even index elements
for(int i = 0; i < N; i += 2)
sum += arr[i];
// Initialize two vectors v1, v2
List<int> v1, v2;
v1 = new List<int>();
v2 = new List<int>();
// v1 will keep account for change
// if 1th index element goes to 0
for(int i = 0; i + 1 < N; i += 2)
v1.Add(arr[i + 1] - arr[i]);
// v2 will keep account for change
// if 1th index element goes to 2
for(int i = 1; i + 1 < N; i += 2)
v2.Add(arr[i] - arr[i + 1]);
// Get the max negative value
int change = Math.Min(after_rev(v1),
after_rev(v2));
if (change < 0)
sum += change;
Console.Write(sum + "\n");
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 0, 1, 4, 3, 0 };
print(arr);
}
}
// This code is contributed by sapnasingh4991
JavaScript
<script>
// Javascript implementation to reverse a subarray
// of the given array to minimize the
// sum of elements at even position
var N = 3;
// Function that will give
// the max negative value
function after_rev(v)
{
var mini = 0, count = 0;
for (var i = 0; i < v.length; i++) {
count += v[i];
// Check for count
// greater than 0
// as we require only
// negative solution
if (count > 0)
count = 0;
if (mini > count)
mini = count;
}
return mini;
}
// Function to print the minimum sum
function print(arr)
{
var sum = 0;
// Taking sum of only
// even index elements
for (var i = 0; i < N; i += 2)
sum += arr[i];
// Initialize two vectors v1, v2
var v1 = [], v2 = [];
// v1 will keep account for change
// if 1th index element goes to 0
for (var i = 0; i + 1 < N; i += 2)
v1.push(arr[i + 1] - arr[i]);
// v2 will keep account for change
// if 1th index element goes to 2
for (var i = 1; i + 1 < N; i += 2)
v2.push(arr[i] - arr[i + 1]);
// Get the max negative value
var change = Math.min(after_rev(v1),
after_rev(v2));
if (change < 0)
sum += change;
document.write( sum );
}
// Driver code
var arr = [0, 1, 4, 3];
print(arr);
// This code is contributed by importantly.
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
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