Elimine los elementos mínimos de cada lado de modo que 2 * min se convierta en más que max

Dada una array no ordenada, recorte la array de modo que el doble del mínimo sea mayor que el máximo en la array recortada. Los elementos deben eliminarse en cualquiera de los extremos de la array.
El número de retiros debe ser mínimo.

Ejemplos: 

arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200}
Output: 4
We need to remove 4 elements (4, 5, 100, 200)
so that 2*min becomes more than max.


arr[] = {4, 7, 5, 6}
Output: 0
We don't need to remove any element as 
4*2 > 7 (Note that min = 4, max = 8)

arr[] = {20, 7, 5, 6}
Output: 1
We need to remove 20 so that 2*min becomes
more than max

arr[] = {20, 4, 1, 3}
Output: 3
We need to remove any three elements from ends
like 20, 4, 1 or 4, 1, 3 or 20, 3, 1 or 20, 4, 1

Le recomendamos encarecidamente que haga clic aquí y lo practique antes de pasar a la solución.

Solución ingenua: 

Una solución ingenua es probar todos los casos posibles utilizando la recurrencia. A continuación se muestra el algoritmo recursivo ingenuo. Tenga en cuenta que el algoritmo solo devuelve el número mínimo de eliminaciones que se deben realizar, no imprime la array recortada. También se puede modificar fácilmente para imprimir la array recortada. 

// Returns minimum number of removals to be made in
// arr[l..h]
minRemovals(int arr[], int l, int h)
1) Find min and max in arr[l..h]
2) If 2*min > max, then return 0.
3) Else return minimum of "minRemovals(arr, l+1, h) + 1"
   and "minRemovals(arr, l, h-1) + 1"

A continuación se muestra la implementación del algoritmo anterior. 

C++

// C++ implementation of above approach
#include <iostream>
using namespace std;
 
// A utility function to find minimum of two numbers
int min(int a, int b) {return (a < b)? a : b;}
 
// A utility function to find minimum in arr[l..h]
int min(int arr[], int l, int h)
{
    int mn = arr[l];
    for (int i=l+1; i<=h; i++)
       if (mn > arr[i])
         mn = arr[i];
    return mn;
}
 
// A utility function to find maximum in arr[l..h]
int max(int arr[], int l, int h)
{
    int mx = arr[l];
    for (int i=l+1; i<=h; i++)
       if (mx < arr[i])
         mx = arr[i];
    return mx;
}
 
// Returns the minimum number of removals from either end
// in arr[l..h] so that 2*min becomes greater than max.
int minRemovals(int arr[], int l, int h)
{
    // If there is 1 or less elements, return 0
    // For a single element, 2*min > max
    // (Assumption: All elements are positive in arr[])
    if (l >= h) return 0;
 
    // 1) Find minimum and maximum in arr[l..h]
    int mn = min(arr, l, h);
    int mx = max(arr, l, h);
 
    //If the property is followed, no removals needed
    if (2*mn > mx)
       return 0;
 
    // Otherwise remove a character from left end and recur,
    // then remove a character from right end and recur, take
    // the minimum of two is returned
    return min(minRemovals(arr, l+1, h),
               minRemovals(arr, l, h-1)) + 1;
}
 
// Driver program to test above functions
int main()
{
  int arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200};
  int n = sizeof(arr)/sizeof(arr[0]);
  cout << minRemovals(arr, 0, n-1);
  return 0;
}

Java

// Java implementation of above approach
class GFG
{
// A utility function to find minimum of two numbers
static int min(int a, int b) {return (a < b)? a : b;}
 
// A utility function to find minimum in arr[l..h]
static int min(int arr[], int l, int h)
{
    int mn = arr[l];
    for (int i=l+1; i<=h; i++)
    if (mn > arr[i])
        mn = arr[i];
    return mn;
}
 
// A utility function to find maximum in arr[l..h]
static int max(int arr[], int l, int h)
{
    int mx = arr[l];
    for (int i=l+1; i<=h; i++)
    if (mx < arr[i])
        mx = arr[i];
    return mx;
}
 
// Returns the minimum number of removals from either end
// in arr[l..h] so that 2*min becomes greater than max.
static int minRemovals(int arr[], int l, int h)
{
    // If there is 1 or less elements, return 0
    // For a single element, 2*min > max
    // (Assumption: All elements are positive in arr[])
    if (l >= h) return 0;
 
    // 1) Find minimum and maximum in arr[l..h]
    int mn = min(arr, l, h);
    int mx = max(arr, l, h);
 
    //If the property is followed, no removals needed
    if (2*mn > mx)
    return 0;
 
    // Otherwise remove a character from left end and recur,
    // then remove a character from right end and recur, take
    // the minimum of two is returned
    return min(minRemovals(arr, l+1, h),
            minRemovals(arr, l, h-1)) + 1;
}
 
// Driver Code
public static void main(String[] args)
{
int arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200};
int n = arr.length;
System.out.print(minRemovals(arr, 0, n-1));
}
}
 
// This code is contributed by Mukul Singh.

Python3

# Python3 implementation of above approach
# A utility function to find
# minimum in arr[l..h]
def mini(arr, l, h):
    mn = arr[l]
    for i in range(l + 1, h + 1):
        if (mn > arr[i]):
            mn = arr[i]
    return mn
 
# A utility function to find
# maximum in arr[l..h]
def max(arr, l, h):
    mx = arr[l]
    for i in range(l + 1, h + 1):
        if (mx < arr[i]):
            mx = arr[i]
    return mx
 
 
# Returns the minimum number of
# removals from either end in
# arr[l..h] so that 2*min becomes
# greater than max.
def minRemovals(arr, l, h):
     
    # If there is 1 or less elements, return 0
    # For a single element, 2*min > max
    # (Assumption: All elements are positive in arr[])
    if (l >= h):
        return 0
 
    # 1) Find minimum and maximum
    #    in arr[l..h]
    mn = mini(arr, l, h)
    mx = max(arr, l, h)
 
    # If the property is followed,
    # no removals needed
    if (2 * mn > mx):
        return 0
 
    # Otherwise remove a character from
    # left end and recur, then remove a
    # character from right end and recur,
    # take the minimum of two is returned
    return (min(minRemovals(arr, l + 1, h),
                minRemovals(arr, l, h - 1)) + 1)
 
# Driver Code
arr = [4, 5, 100, 9, 10,
       11, 12, 15, 200]
n = len(arr)
print(minRemovals(arr, 0, n - 1))
 
# This code is contributed
# by sahilshelangia

C#

// C# implementation of above approach
using System;
 
class GFG
{
// A utility function to find minimum of two numbers
static int min(int a, int b) {return (a < b)? a : b;}
 
// A utility function to find minimum in arr[l..h]
static int min(int[] arr, int l, int h)
{
    int mn = arr[l];
    for (int i=l+1; i<=h; i++)
    if (mn > arr[i])
        mn = arr[i];
    return mn;
}
 
// A utility function to find maximum in arr[l..h]
static int max(int[] arr, int l, int h)
{
    int mx = arr[l];
    for (int i=l+1; i<=h; i++)
    if (mx < arr[i])
        mx = arr[i];
    return mx;
}
 
// Returns the minimum number of removals from either end
// in arr[l..h] so that 2*min becomes greater than max.
static int minRemovals(int[] arr, int l, int h)
{
    // If there is 1 or less elements, return 0
    // For a single element, 2*min > max
    // (Assumption: All elements are positive in arr[])
    if (l >= h) return 0;
 
    // 1) Find minimum and maximum in arr[l..h]
    int mn = min(arr, l, h);
    int mx = max(arr, l, h);
 
    //If the property is followed, no removals needed
    if (2*mn > mx)
    return 0;
 
    // Otherwise remove a character from left end and recur,
    // then remove a character from right end and recur, take
    // the minimum of two is returned
    return min(minRemovals(arr, l+1, h),
            minRemovals(arr, l, h-1)) + 1;
}
 
// Driver Code
public static void Main()
{
int[] arr = {4, 5, 100, 9, 10, 11, 12, 15, 200};
int n = arr.Length;
Console.Write(minRemovals(arr, 0, n-1));
}
}
 
// This code is contributed by Akanksha Rai

PHP

<?php
// PHP implementation of above approach
 
// A utility function to find
// minimum in arr[l..h]
function min_1(&$arr, $l, $h)
{
    $mn = $arr[$l];
    for ($i = $l + 1; $i <= $h; $i++)
    if ($mn > $arr[$i])
        $mn = $arr[$i];
    return $mn;
}
 
// A utility function to find
// maximum in arr[l..h]
function max_1(&$arr, $l, $h)
{
    $mx = $arr[$l];
    for ($i = $l + 1; $i <= $h; $i++)
    if ($mx < $arr[$i])
        $mx = $arr[$i];
    return $mx;
}
 
// Returns the minimum number of removals
// from either end in arr[l..h] so that
// 2*min becomes greater than max.
function minRemovals(&$arr, $l, $h)
{
    // If there is 1 or less elements,
    // return 0. For a single element,
    // 2*min > max. (Assumption: All
    // elements are positive in arr[])
    if ($l >= $h) return 0;
 
    // 1) Find minimum and maximum in arr[l..h]
    $mn = min_1($arr, $l, $h);
    $mx = max_1($arr, $l, $h);
 
    // If the property is followed,
    // no removals needed
    if (2 * $mn > $mx)
    return 0;
 
    // Otherwise remove a character from left
    // end and recur, then remove a character
    // from right end and recur, take the
    // minimum of two is returned
    return min(minRemovals($arr, $l + 1, $h),
               minRemovals($arr, $l, $h - 1)) + 1;
}
 
// Driver Code
$arr = array(4, 5, 100, 9, 10,
             11, 12, 15, 200);
$n = sizeof($arr);
echo minRemovals($arr, 0, $n - 1);
 
// This code is contributed
// by ChitraNayal
?>

Javascript

<script>
     
    // A utility function to find minimum in arr[l..h]
    function min(arr,l,h)
    {
        let mn = arr[l];
        for (let i=l+1; i<=h; i++)
        {
            if (mn > arr[i])
                mn = arr[i];
        }
        return mn;
    }
     
    // A utility function to find maximum in arr[l..h]
    function max(arr,l,h)
    {
        let mx = arr[l];
        for (let i=l+1; i<=h; i++)
        {
            if (mx < arr[i])
                mx = arr[i];
        }
        return mx;
    }
     
    // Returns the minimum number of removals from either end
    // in arr[l..h] so that 2*min becomes greater than max.
    function minRemovals(arr,l,h)
    {
     
        // If there is 1 or less elements, return 0
        // For a single element, 2*min > max
        // (Assumption: All elements are positive in arr[])
        if (l >= h)
            return 0;
         
        // 1) Find minimum and maximum in arr[l..h]
        let mn = min(arr, l, h);
        let mx = max(arr, l, h);
         
        // If the property is followed, no removals needed
        if (2*mn > mx)
            return 0;
         
        // Otherwise remove a character from left end and recur,
        // then remove a character from right end and recur, take
        // the minimum of two is returned
        return Math.min(minRemovals(arr, l+1, h),minRemovals(arr, l, h-1)) + 1;
    }
     
    // Driver Code
    let arr = [4, 5, 100, 9, 10, 11, 12, 15, 200];
    let n = arr.length;
    document.write(minRemovals(arr, 0, n - 1));
     
    // This code is contributed by rag2127
</script>
Producción

4

Complejidad del tiempo: la complejidad del tiempo de la función anterior se puede escribir de la siguiente manera

  T(n) = 2T(n-1) + O(n) 

Un límite superior en la solución de la recurrencia anterior sería O(nx 2 n ).

Programación dinámica: 

El código recursivo anterior presenta muchos subproblemas superpuestos. Por ejemplo, minRemovals(arr, l+1, h-1) se evalúa dos veces. Entonces, la Programación Dinámica es la elección para optimizar la solución. La siguiente es una solución basada en programación dinámica. 

C++

// C++ program of above approach
#include <iostream>
using namespace std;
 
// A utility function to find minimum of two numbers
int min(int a, int b) {return (a < b)? a : b;}
 
// A utility function to find minimum in arr[l..h]
int min(int arr[], int l, int h)
{
    int mn = arr[l];
    for (int i=l+1; i<=h; i++)
       if (mn > arr[i])
         mn = arr[i];
    return mn;
}
 
// A utility function to find maximum in arr[l..h]
int max(int arr[], int l, int h)
{
    int mx = arr[l];
    for (int i=l+1; i<=h; i++)
       if (mx < arr[i])
         mx = arr[i];
    return mx;
}
 
// Returns the minimum number of removals from either end
// in arr[l..h] so that 2*min becomes greater than max.
int minRemovalsDP(int arr[], int n)
{
    // Create a table to store solutions of subproblems
    int table[n][n], gap, i, j, mn, mx;
 
    // Fill table using above recursive formula. Note that the table
    // is filled in diagonal fashion (similar to http://goo.gl/PQqoS),
    // from diagonal elements to table[0][n-1] which is the result.
    for (gap = 0; gap < n; ++gap)
    {
        for (i = 0, j = gap; j < n; ++i, ++j)
        {
            mn = min(arr, i, j);
            mx = max(arr, i, j);
            table[i][j] = (2*mn > mx)? 0: min(table[i][j-1]+1,
                                              table[i+1][j]+1);
        }
    }
    return table[0][n-1];
}
 
// Driver program to test above functions
int main()
{
  int arr[] = {20, 4, 1, 3};
  int n = sizeof(arr)/sizeof(arr[0]);
  cout << minRemovalsDP(arr, n);
  return 0;
}

Java

// Java program of above approach
class GFG {
 
// A utility function to find minimum of two numbers
    static int min(int a, int b) {
        return (a < b) ? a : b;
    }
 
// A utility function to find minimum in arr[l..h]
    static int min(int arr[], int l, int h) {
        int mn = arr[l];
        for (int i = l + 1; i <= h; i++) {
            if (mn > arr[i]) {
                mn = arr[i];
            }
        }
        return mn;
    }
 
// A utility function to find maximum in arr[l..h]
    static int max(int arr[], int l, int h) {
        int mx = arr[l];
        for (int i = l + 1; i <= h; i++) {
            if (mx < arr[i]) {
                mx = arr[i];
            }
        }
        return mx;
    }
 
// Returns the minimum number of removals from either end
// in arr[l..h] so that 2*min becomes greater than max.
    static int minRemovalsDP(int arr[], int n) {
        // Create a table to store solutions of subproblems
        int table[][] = new int[n][n], gap, i, j, mn, mx;
 
        // Fill table using above recursive formula. Note that the table
        // is filled in diagonal fashion (similar to http://goo.gl/PQqoS),
        // from diagonal elements to table[0][n-1] which is the result.
        for (gap = 0; gap < n; ++gap) {
            for (i = 0, j = gap; j < n; ++i, ++j) {
                mn = min(arr, i, j);
                mx = max(arr, i, j);
                table[i][j] = (2 * mn > mx) ? 0 : min(table[i][j - 1] + 1,
                        table[i + 1][j] + 1);
            }
        }
        return table[0][n - 1];
    }
 
// Driver program to test above functions
    public static void main(String[] args) {
        int arr[] = {20, 4, 1, 3};
        int n = arr.length;
        System.out.println(minRemovalsDP(arr, n));
 
    }
}
// This code contributed by 29AJayKumar

Python3

# Python3 program of above approach
 
# A utility function to find
# minimum in arr[l..h]
def min1(arr, l, h):
    mn = arr[l];
    for i in range(l + 1,h+1):
        if (mn > arr[i]):
            mn = arr[i];
    return mn;
 
# A utility function to find
# maximum in arr[l..h]
def max1(arr, l, h):
    mx = arr[l];
    for i in range(l + 1, h + 1):
        if (mx < arr[i]):
            mx = arr[i];
    return mx;
 
# Returns the minimum number of removals
# from either end in arr[l..h] so that
# 2*min becomes greater than max.
def minRemovalsDP(arr, n):
     
    # Create a table to store
    # solutions of subproblems
    table = [[0 for x in range(n)] for y in range(n)];
     
    # Fill table using above recursive formula.
    # Note that the table is filled in diagonal fashion
    # (similar to http:#goo.gl/PQqoS), from diagonal elements
    # to table[0][n-1] which is the result.
    for gap in range(n):
        i = 0;
        for j in range(gap,n):
            mn = min1(arr, i, j);
            mx = max1(arr, i, j);
            table[i][j] = 0 if (2 * mn > mx) else min(table[i][j - 1] + 1,table[i + 1][j] + 1);
            i += 1;
    return table[0][n - 1];
 
# Driver Code
arr = [20, 4, 1, 3];
n = len(arr);
print(minRemovalsDP(arr, n));
 
# This code is contributed by mits

C#

// C# program of above approach
using System;
 
public class GFG {
  
    // A utility function to find minimum of two numbers
    static int min(int a, int b) {
        return (a < b) ? a : b;
    }
  
    // A utility function to find minimum in arr[l..h]
    static int min(int []arr, int l, int h) {
        int mn = arr[l];
        for (int i = l + 1; i <= h; i++) {
            if (mn > arr[i]) {
                mn = arr[i];
            }
        }
        return mn;
    }
  
// A utility function to find maximum in arr[l..h]
    static int max(int []arr, int l, int h) {
        int mx = arr[l];
        for (int i = l + 1; i <= h; i++) {
            if (mx < arr[i]) {
                mx = arr[i];
            }
        }
        return mx;
    }
  
    // Returns the minimum number of removals from either end
    // in arr[l..h] so that 2*min becomes greater than max.
    static int minRemovalsDP(int []arr, int n) {
        // Create a table to store solutions of subproblems
        int [,]table = new int[n,n];
        int gap, i, j, mn, mx;
  
        // Fill table using above recursive formula. Note that the table
        // is filled in diagonal fashion (similar to http://goo.gl/PQqoS),
        // from diagonal elements to table[0][n-1] which is the result.
        for (gap = 0; gap < n; ++gap) {
            for (i = 0, j = gap; j < n; ++i, ++j) {
                mn = min(arr, i, j);
                mx = max(arr, i, j);
                table[i,j] = (2 * mn > mx) ? 0 : min(table[i,j - 1] + 1,
                        table[i + 1,j] + 1);
            }
        }
        return table[0,n - 1];
    }
  
    // Driver program to test above functions
    public static void Main() {
        int []arr = {20, 4, 1, 3};
        int n = arr.Length;
        Console.WriteLine(minRemovalsDP(arr, n));
  
    }
}
// This code contributed by 29AJayKumar

PHP

<?php
// PHP program of above approach
 
// A utility function to find
// minimum in arr[l..h]
function min1($arr, $l, $h)
{
    $mn = $arr[$l];
    for ($i = $l + 1; $i <= $h; $i++)
    if ($mn > $arr[$i])
        $mn = $arr[$i];
    return $mn;
}
 
// A utility function to find
// maximum in arr[l..h]
function max1($arr, $l, $h)
{
    $mx = $arr[$l];
    for ($i = $l + 1; $i <= $h; $i++)
    if ($mx < $arr[$i])
        $mx = $arr[$i];
    return $mx;
}
 
// Returns the minimum number of removals
// from either end in arr[l..h] so that
// 2*min becomes greater than max.
function minRemovalsDP($arr, $n)
{
     
    // Create a table to store
    // solutions of subproblems
    $table = array_fill(0, $n,
             array_fill(0, $n, 0));
 
    // Fill table using above recursive formula.
    // Note that the table is filled in diagonal fashion
    // (similar to http://goo.gl/PQqoS), from diagonal elements
    // to table[0][n-1] which is the result.
    for ($gap = 0; $gap < $n; ++$gap)
    {
        for ($i = 0, $j = $gap; $j < $n; ++$i, ++$j)
        {
            $mn = min1($arr, $i, $j);
            $mx = max1($arr, $i, $j);
            $table[$i][$j] = (2 * $mn > $mx) ? 0 :
                              min($table[$i][$j - 1] + 1,
                                  $table[$i + 1][$j] + 1);
        }
    }
    return $table[0][$n - 1];
}
 
// Driver Code
$arr = array(20, 4, 1, 3);
$n = count($arr);
echo minRemovalsDP($arr, $n);
 
// This code is contributed by mits
?>

Javascript

<script>
 
// Javascript program of above approach   
 
// A utility function to find minimum
// of two numbers
function minq(a, b)
{
    return (a < b) ? a : b;
}
 
// A utility function to find minimum
// in arr[l..h]
function min(arr, l, h)
{
    var mn = arr[l];
    for(i = l + 1; i <= h; i++)
    {
        if (mn > arr[i])
        {
            mn = arr[i];
        }
    }
    return parseInt(mn);
}
 
// A utility function to find maximum in arr[l..h]
function max(arr, l, h)
{
    var mx = arr[l];
    for(i = l + 1; i <= h; i++)
    {
        if (mx < arr[i])
        {
            mx = arr[i];
        }
    }
    return parseInt(mx);
}
 
// Returns the minimum number of removals
// from either end in arr[l..h] so that
// 2*min becomes greater than max.
function minRemovalsDP(arr, n)
{
     
    // Create a table to store solutions
    // of subproblems
    var table = Array(n);
    var gap, i, j, mn, mx;
     
    for(i = 0; i < n; i++)
        table[i] = Array(n).fill(0);
 
    // Fill table using above recursive formula.
    // Note that the table is filled in diagonal
    // fashion (similar to http://goo.gl/PQqoS),
    // from diagonal elements to table[0][n-1]
    // which is the result.
    for(gap = 0; gap < n; ++gap)
    {
        for(i = 0, j = gap; j < n; ++i, ++j)
        {
            mn = min(arr, i, j);
            mx = max(arr, i, j);
            table[i][j] = parseInt((2 * mn > mx) ?
                  0 : minq(table[i][j - 1] + 1,
                           table[i + 1][j] + 1));
        }
    }
    return table[0][n - 1];
}
 
// Driver code
var arr = [ 20, 4, 1, 3 ];
var n = arr.length;
 
document.write(minRemovalsDP(arr, n));
 
// This code is contributed by gauravrajput1
 
</script>
Producción

3

Complejidad temporal: O(n 3 ) donde n es el número de elementos en arr[]. 

Más optimizaciones: 

El código anterior se puede optimizar de muchas maneras. 

  1. Podemos evitar el cálculo de min() y/o max() cuando min y/o max no se modifican eliminando los elementos de las esquinas.
  2. Podemos preprocesar la array y construir un árbol de segmentos en tiempo O(n). Después de construir el árbol de segmentos, podemos consultar el rango mínimo y máximo en el tiempo O (Inicio de sesión). La complejidad total del tiempo se reduce al tiempo O(n 2 Logn).

AO(n^2) Solución:

La idea es encontrar el subarreglo de tamaño máximo tal que 2*min > max. Ejecutamos dos bucles anidados, el bucle exterior elige un punto de inicio y el bucle interior elige el punto final para el punto de inicio actual. Realizamos un seguimiento del subarreglo más largo con la propiedad dada.

A continuación se muestra la implementación del enfoque anterior. Gracias a Richard Zhang por sugerir esta solución. 

C++

// A O(n*n) solution to find the minimum of elements to
// be removed
#include <iostream>
#include <climits>
using namespace std;
 
// Returns the minimum number of removals from either end
// in arr[l..h] so that 2*min becomes greater than max.
int minRemovalsDP(int arr[], int n)
{
    // Initialize starting and ending indexes of the maximum
    // sized subarray with property 2*min > max
    int longest_start = -1, longest_end = 0;
 
    // Choose different elements as starting point
    for (int start=0; start<n; start++)
    {
        // Initialize min and max for the current start
        int min = INT_MAX, max = INT_MIN;
 
        // Choose different ending points for current start
        for (int end = start; end < n; end ++)
        {
            // Update min and max if necessary
            int val = arr[end];
            if (val < min) min = val;
            if (val > max) max = val;
 
            // If the property is violated, then no
            // point to continue for a bigger array
            if (2 * min <= max) break;
 
            // Update longest_start and longest_end if needed
            if (end - start > longest_end - longest_start ||
                longest_start == -1)
            {
                longest_start = start;
                longest_end = end;
            }
        }
    }
 
    // If not even a single element follow the property,
    // then return n
    if (longest_start == -1) return n;
 
    // Return the number of elements to be removed
    return (n - (longest_end - longest_start + 1));
}
 
// Driver program to test above functions
int main()
{
    int arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << minRemovalsDP(arr, n);
    return 0;
}

Java

// A O(n*n) solution to find the minimum of elements to
// be removed
 
class GFG {
 
// Returns the minimum number of removals from either end
// in arr[l..h] so that 2*min becomes greater than max.
    static int minRemovalsDP(int arr[], int n) {
        // Initialize starting and ending indexes of the maximum
        // sized subarray with property 2*min > max
        int longest_start = -1, longest_end = 0;
 
        // Choose different elements as starting point
        for (int start = 0; start < n; start++) {
            // Initialize min and max for the current start
            int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
 
            // Choose different ending points for current start
            for (int end = start; end < n; end++) {
                // Update min and max if necessary
                int val = arr[end];
                if (val < min) {
                    min = val;
                }
                if (val > max) {
                    max = val;
                }
 
                // If the property is violated, then no
                // point to continue for a bigger array
                if (2 * min <= max) {
                    break;
                }
 
                // Update longest_start and longest_end if needed
                if (end - start > longest_end - longest_start
                        || longest_start == -1) {
                    longest_start = start;
                    longest_end = end;
                }
            }
        }
 
        // If not even a single element follow the property,
        // then return n
        if (longest_start == -1) {
            return n;
        }
 
        // Return the number of elements to be removed
        return (n - (longest_end - longest_start + 1));
    }
 
// Driver program to test above functions
    public static void main(String[] args) {
        int arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200};
        int n = arr.length;
        System.out.println(minRemovalsDP(arr, n));
    }
}
 
// This code is contributed by PrinciRaj1992

Python3

# A O(n*n) solution to find the minimum of
# elements to be removed
import sys;
 
# Returns the minimum number of removals
# from either end in arr[l..h] so that
# 2*min becomes greater than max.
def minRemovalsDP(arr, n):
 
    # Initialize starting and ending indexes
    # of the maximum sized subarray
    # with property 2*min > max
    longest_start = -1;
    longest_end = 0;
 
    # Choose different elements as starting point
    for start in range(n):
         
        # Initialize min and max
        # for the current start
        min = sys.maxsize;
        max = -sys.maxsize;
 
        # Choose different ending points for current start
        for end in range(start,n):
            # Update min and max if necessary
            val = arr[end];
            if (val < min):
                min = val;
            if (val > max):
                max = val;
 
            # If the property is violated, then no
            # point to continue for a bigger array
            if (2 * min <= max):
                break;
 
            # Update longest_start and longest_end if needed
            if (end - start > longest_end - longest_start or longest_start == -1):
                longest_start = start;
                longest_end = end;
 
    # If not even a single element follow the property,
    # then return n
    if (longest_start == -1):
        return n;
 
    # Return the number of elements to be removed
    return (n - (longest_end - longest_start + 1));
 
# Driver Code
arr = [4, 5, 100, 9, 10, 11, 12, 15, 200];
n = len(arr);
print(minRemovalsDP(arr, n));
 
# This code is contributed by mits

C#

// A O(n*n) solution to find the minimum of elements to
// be removed
 
using System;
public class GFG {
  
// Returns the minimum number of removals from either end
// in arr[l..h] so that 2*min becomes greater than max.
    static int minRemovalsDP(int []arr, int n) {
        // Initialize starting and ending indexes of the maximum
        // sized subarray with property 2*min > max
        int longest_start = -1, longest_end = 0;
  
        // Choose different elements as starting point
        for (int start = 0; start < n; start++) {
            // Initialize min and max for the current start
            int min = int.MaxValue, max = int.MinValue;
  
            // Choose different ending points for current start
            for (int end = start; end < n; end++) {
                // Update min and max if necessary
                int val = arr[end];
                if (val < min) {
                    min = val;
                }
                if (val > max) {
                    max = val;
                }
  
                // If the property is violated, then no
                // point to continue for a bigger array
                if (2 * min <= max) {
                    break;
                }
  
                // Update longest_start and longest_end if needed
                if (end - start > longest_end - longest_start
                        || longest_start == -1) {
                    longest_start = start;
                    longest_end = end;
                }
            }
        }
  
        // If not even a single element follow the property,
        // then return n
        if (longest_start == -1) {
            return n;
        }
  
        // Return the number of elements to be removed
        return (n - (longest_end - longest_start + 1));
    }
  
// Driver program to test above functions
    public static void Main() {
        int []arr = {4, 5, 100, 9, 10, 11, 12, 15, 200};
        int n = arr.Length;
        Console.WriteLine(minRemovalsDP(arr, n));
    }
}
  
// This code is contributed by Rajput-Ji

PHP

<?php
// A O(n*n) solution to find the minimum of
// elements to be removed
 
// Returns the minimum number of removals
// from either end in arr[l..h] so that
// 2*min becomes greater than max.
function minRemovalsDP($arr, $n)
{
    // Initialize starting and ending indexes
    // of the maximum sized subarray
    // with property 2*min > max
    $longest_start = -1;
    $longest_end = 0;
 
    // Choose different elements as starting point
    for ($start = 0; $start < $n; $start++)
    {
         
        // Initialize min and max
        // for the current start
        $min = PHP_INT_MAX;
        $max = PHP_INT_MIN;
 
        // Choose different ending points for current start
        for ($end = $start; $end < $n; $end ++)
        {
            // Update min and max if necessary
            $val = $arr[$end];
            if ($val < $min) $min = $val;
            if ($val > $max) $max = $val;
 
            // If the property is violated, then no
            // point to continue for a bigger array
            if (2 * $min <= $max) break;
 
            // Update longest_start and longest_end if needed
            if ($end - $start > $longest_end - $longest_start ||
                $longest_start == -1)
            {
                $longest_start = $start;
                $longest_end = $end;
            }
        }
    }
 
    // If not even a single element follow the property,
    // then return n
    if ($longest_start == -1) return $n;
 
    // Return the number of elements to be removed
    return ($n - ($longest_end - $longest_start + 1));
}
 
// Driver Code
$arr = array(4, 5, 100, 9, 10, 11, 12, 15, 200);
$n = sizeof($arr);
echo minRemovalsDP($arr, $n);
 
// This code is contributed by jit_t
?>

Javascript

<script>
 
// A O(n*n) solution to find the minimum of elements to
// be removed
 
    // Returns the minimum number of removals from either end
    // in arr[l..h] so that 2*min becomes greater than max.
    function minRemovalsDP(arr,n)
    {
        // Initialize starting and ending indexes of the maximum
        // sized subarray with property 2*min > max
        let longest_start = -1, longest_end = 0;
         
        // Choose different elements as starting point
        for (let start = 0; start < n; start++)
        {
            // Initialize min and max for the current start
            let  min = Number.MAX_VALUE, max = Number.MIN_VALUE;
             
            // Choose different ending points for current start
            for (let end = start; end < n; end++)
            {
                // Update min and max if necessary
                let val = arr[end];
                if (val < min)
                {
                    min = val;
                }
                if (val > max)
                {
                    max = val;
                }
                // If the property is violated, then no
                // point to continue for a bigger array
                if (2 * min <= max)
                {
                    break;
                }
                 
                // Update longest_start and longest_end if needed
                if (end - start > longest_end - longest_start
                        || longest_start == -1)
                {
                    longest_start = start;
                    longest_end = end;
                }
                 
            }
        }
        // If not even a single element follow the property,
        // then return n
        if (longest_start == -1)
        {
            return n;
        }
        // Return the number of elements to be removed
        return (n - (longest_end - longest_start + 1));
    }
     
    // Driver program to test above functions
    let arr=[4, 5, 100, 9, 10, 11, 12, 15, 200];
    let n = arr.length;
    document.write(minRemovalsDP(arr, n));
     
     
    // This code is contributed by avanitrachhadiya2155
     
</script>
Producción

4

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *