# Reverse a subarray of the given array to minimize the sum of elements at even position

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:
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:
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 ` `#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);`

Output

```1

```

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 ` `#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 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 v1, v2;` `    ``v1 = ``new` `Vector();` `    ``v2 = ``new` `Vector();` `    `  `    ``// 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

 ``

Output

```1

```

Time Complexity: O(N)
Auxiliary Space: O(N)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!