Reverse a subarray of the given array to minimize the sum of elements at even position
Last Updated :
16 Oct, 2023
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
Reverse a subarray to maximize sum of even-indexed elements of given array Given an array arr[], the task is to maximize the sum of even-indexed elements by reversing a subarray and print the maximum sum obtained. Examples: Input: arr[] = {1, 2, 1, 2, 1} Output: 5 Explanation: Sum of initial even-indexed elements = a[0] + a[2] + a[4] = 1 + 1 + 1 = 3 Reversing subarray {1,
9 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4,
12 min read
Maximize the difference of sum of elements at even indices and odd indices by shifting an odd sized subarray to end of given Array. Given an array arr[] of size N, the task is to maximize the difference of the sum of elements at even indices and elements at odd indices by shifting any subarray of odd length to the end of the array. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}Output: 3Explanation: Initially sum of elements at even
13 min read
Rearrange Array to minimize difference of sum of squares of odd and even index elements Given an array arr[] of size N (multiple of 8) where the values in the array will be in the range [a, (a+8*N) -1] (a can be any positive integer), the task is to rearrange the array in a way such that the difference between the sum of squares at odd indices and sum of squares of the elements at even
15+ min read
Make all the elements of array even with given operations Given an array arr[] of positive integers, find the minimum number of operations required to make all the array elements even where: If there is an odd number, then, increment the element and the next adjacent element by 1.Each increment costs one operation. Note: If there is any number in arr[] whi
6 min read
Maximize the count of adjacent element pairs with even sum by rearranging the Array Given an array, arr[] of N integers, the task is to find the maximum possible count of adjacent pairs with an even sum, rearranging the array arr[]. Examples: Input: arr[] = {5, 5, 1}Output: 2Explanation:The given array is already arranged to give the maximum count of adjacent pairs with an even sum
6 min read
Minimum possible sum of array elements after performing the given operation Given an array arr[] of size N and a number X. If any sub array of the array(possibly empty) arr[i], arr[i+1], ... can be replaced with arr[i]/x, arr[i+1]/x, .... The task is to find the minimum possible sum of the array which can be obtained. Note: The given operation can only be performed once.Exa
9 min read
Count subarrays having sum of elements at even and odd positions equal Given an array arr[] of integers, the task is to find the total count of subarrays such that the sum of elements at even position and sum of elements at the odd positions are equal. Examples: Input: arr[] = {1, 2, 3, 4, 1}Output: 1Explanation: {3, 4, 1} is the only subarray in which sum of elements
6 min read
Rearrange an array to minimize sum of product of consecutive pair elements We are given an array of even size, we have to sort the array in such a way that the sum of product of alternate elements is minimum also we have to find that minimum sum. Examples: Input : arr[] = {9, 2, 8, 4, 5, 7, 6, 0} Output : Minimum sum of the product of consecutive pair elements: 74 Sorted a
7 min read
Minimize count of flips required to make sum of the given array equal to 0 Given an array arr[] consisting of N integers, the task is to minimize the count of elements required to be multiplied by -1 such that the sum of array elements is 0. If it is not possible to make the sum 0, print "-1". Examples: Input: arr[] = {2, 3, 1, 4}Output: 2Explanation: Multiply arr[0] by -1
15+ min read