📌  相关文章
📜  反转给定数组的子数组以最小化偶数位置的元素总和

📅  最后修改于: 2021-10-26 05:32:35             🧑  作者: Mango

给定一个由正整数组成的数组 arr[] 。任务是反转子数组以最小化偶数位置的元素总和并打印最小总和。

注意:只执行一次移动。子阵列可能无法反转。

例子:

朴素方法:想法是应用蛮力方法并生成所有子数组并检查偶数位置的元素总和。打印所有中最小的和。

时间复杂度: O(N 3 )
辅助空间: O(N)

高效的方法:想法是观察数组arr[]的以下要点:

  • 反转奇数长度的子数组不会改变总和,因为偶数索引处的所有元素将再次到达偶数索引。
  • 反转偶数长度子数组将使索引位置的所有元素都变为偶数索引,而偶数索引处的元素将变为奇数索引。
  • 仅当将奇数索引元素放在偶数索引元素上时,元素总和才会改变。假设索引 1 处的元素可以转到索引 0 或索引 2。
  • 在从偶数索引反转到另一个偶数索引示例从索引 2 到 4 时,它将覆盖第一种情况,或者如果从奇数索引到偶数索引示例从索引 1 到 4,它将覆盖第二种情况。

以下是基于上述观察结果的方法步骤:

  • 因此,我们的想法是找到仅偶数索引元素的总和并初始化两个数组,例如v1v2,这样如果第一个索引元素变为 0,v1 将保留更改,而如果第一个索引元素变为 v2 将保留更改的帐户到 2。
  • 获取两个值中的最小值并检查它是否小于 0。如果是,则将其添加到答案中,最后返回答案。

下面是上述方法的实现:

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


输出:
1

时间复杂度: O(N)
辅助空间: O(N)