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

📅  最后修改于: 2021-05-17 22:53:32             🧑  作者: 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
        // 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 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 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 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 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 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 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


输出:
1


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