Skip to content
Related Articles

Related Articles

Improve Article
Reverse a subarray of the given array to minimize the sum of elements at even position
  • Last Updated : 03 Jun, 2021

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 subarray and check the sum of elements at the even position. Print the sum which is the minimum among all.
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
        // graeter 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 accout 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 graeter
        // 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 accout 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 graeter
        # 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 accout 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 graeter
        // 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 accout 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
        // graeter 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 accout 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>
Output: 
1

 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 




My Personal Notes arrow_drop_up
Recommended Articles
Page :