Open In App

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++ 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;
}




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);
    }
}




# 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)




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);
    }
}




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[]:  

Below are the steps of the approach based on the above observations:  

Below is the implementation of the above approach : 




// 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 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 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# 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




<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>

Output
1







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


Article Tags :