Minimice la suma dividiendo todos los elementos de un subarreglo por K

Dada una array arr[] de N enteros y un entero positivo K , la tarea es minimizar la suma de los elementos de la array después de realizar la operación dada al menos una vez . La operación es elegir un subarreglo y dividir todos los elementos del subarreglo por K . Encuentre e imprima la suma mínima posible.
Ejemplos: 
 

Entrada: arr[] = {1, -2, 3}, K = 2 
Salida: 0.5 
Elija el subarreglo {3} y divídalo por K 
El arreglo se convierte en {1, -2, 1.5} donde 1 – 2 + 1.5 = 0.5
Entrada: arr[] = {-1, -2, -3, -5}, K = 4 
Salida: -11 
No es necesario realizar la operación ya que la 
suma de los elementos de la array ya es mínima. 
 

Acercarse: 
 

  • Encuentre el subarreglo de suma máxima utilizando el algoritmo de Kadane , diga maxSum , ya que será el subarreglo que contribuirá a maximizar la suma del arreglo.
  • Ahora hay dos casos: 
    1. maxSum > 0: Divide cada elemento del subarreglo encontrado con K y la suma del arreglo resultante será la mínima posible.
    2. maxSum ≤ 0: No es necesario realizar la operación ya que la suma de la array ya es mínima.

A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the maximum subarray sum
int maxSubArraySum(int a[], int size)
{
    int max_so_far = INT_MIN, max_ending_here = 0;
 
    for (int i = 0; i < size; i++) {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
 
        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
}
 
// Function to return the minimized sum
// of the array elements after performing
// the given operation
double minimizedSum(int a[], int n, int K)
{
 
    // Find maximum subarray sum
    int sum = maxSubArraySum(a, n);
    double totalSum = 0;
 
    // Find total sum of the array
    for (int i = 0; i < n; i++)
        totalSum += a[i];
 
    // Maximum subarray sum is already negative
    if (sum < 0)
        return totalSum;
 
    // Choose the subarray whose sum is
    // maximum and divide all elements by K
    totalSum = totalSum - sum + (double)sum / (double)K;
    return totalSum;
}
 
// Driver code
int main()
{
 
    int a[] = { 1, -2, 3 };
    int n = sizeof(a) / sizeof(a[0]);
    int K = 2;
 
    cout << minimizedSum(a, n, K);
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
class GFG
{
 
// Function to return the maximum subarray sum
static int maxSubArraySum(int a[], int size)
{
    int max_so_far = Integer.MIN_VALUE,
        max_ending_here = 0;
 
    for (int i = 0; i < size; i++)
    {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
 
        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
}
 
// Function to return the minimized sum
// of the array elements after performing
// the given operation
static double minimizedSum(int a[], int n, int K)
{
 
    // Find maximum subarray sum
    int sum = maxSubArraySum(a, n);
    double totalSum = 0;
 
    // Find total sum of the array
    for (int i = 0; i < n; i++)
        totalSum += a[i];
 
    // Maximum subarray sum is already negative
    if (sum < 0)
        return totalSum;
 
    // Choose the subarray whose sum is
    // maximum and divide all elements by K
    totalSum = totalSum - sum + (double)sum /
                                (double)K;
    return totalSum;
}
 
// Driver code
public static void main(String []args)
{
    int a[] = { 1, -2, 3 };
    int n = a.length;
    int K = 2;
 
    System.out.println(minimizedSum(a, n, K));
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 implementation of the approach
import sys
 
# Function to return the maximum subarray sum
def maxSubArraySum(a, size) :
 
    max_so_far = -(sys.maxsize - 1);
    max_ending_here = 0;
 
    for i in range(size) :
         
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here) :
            max_so_far = max_ending_here;
 
        if (max_ending_here < 0) :
            max_ending_here = 0;
 
    return max_so_far;
 
# Function to return the minimized sum
# of the array elements after performing
# the given operation
def minimizedSum(a, n, K) :
 
    # Find maximum subarray sum
    sum = maxSubArraySum(a, n);
    totalSum = 0;
 
    # Find total sum of the array
    for i in range(n) :
        totalSum += a[i];
 
    # Maximum subarray sum is already negative
    if (sum < 0) :
        return totalSum;
 
    # Choose the subarray whose sum is
    # maximum and divide all elements by K
    totalSum = totalSum - sum + sum / K;
     
    return totalSum;
 
# Driver code
if __name__ == "__main__" :
 
    a = [ 1, -2, 3 ];
    n = len(a);
    K = 2;
 
    print(minimizedSum(a, n, K));
 
# This code is contributed by AnkitRai01

C#

// C# implementation of the approach
using System;
                     
class GFG
{
 
// Function to return the maximum subarray sum
static int maxSubArraySum(int []a, int size)
{
    int max_so_far = int.MinValue,
        max_ending_here = 0;
 
    for (int i = 0; i < size; i++)
    {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
 
        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
}
 
// Function to return the minimized sum
// of the array elements after performing
// the given operation
static double minimizedSum(int []a, int n, int K)
{
 
    // Find maximum subarray sum
    int sum = maxSubArraySum(a, n);
    double totalSum = 0;
 
    // Find total sum of the array
    for (int i = 0; i < n; i++)
        totalSum += a[i];
 
    // Maximum subarray sum is already negative
    if (sum < 0)
        return totalSum;
 
    // Choose the subarray whose sum is
    // maximum and divide all elements by K
    totalSum = totalSum - sum + (double)sum /
                                (double)K;
    return totalSum;
}
 
// Driver code
public static void Main(String []args)
{
    int []a = { 1, -2, 3 };
    int n = a.Length;
    int K = 2;
 
    Console.WriteLine(minimizedSum(a, n, K));
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
 
// Javascript implementation of the approach
 
// Function to return the maximum subarray sum
function maxSubArraySum(a, size)
{
    var max_so_far = -1000000000, max_ending_here = 0;
 
    for (var i = 0; i < size; i++) {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
 
        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
}
 
// Function to return the minimized sum
// of the array elements after performing
// the given operation
function minimizedSum(a, n, K)
{
 
    // Find maximum subarray sum
    var sum = maxSubArraySum(a, n);
    var totalSum = 0;
 
    // Find total sum of the array
    for (var i = 0; i < n; i++)
        totalSum += a[i];
 
    // Maximum subarray sum is already negative
    if (sum < 0)
        return totalSum;
 
    // Choose the subarray whose sum is
    // maximum and divide all elements by K
    totalSum = totalSum - sum + sum / K;
    return totalSum;
}
 
// Driver code
var a = [1, -2, 3];
var n = a.length;
var K = 2;
document.write( minimizedSum(a, n, K));
 
// This code is contributed by rrrtnx.
</script>
Producción: 

0.5

 

Complejidad de tiempo: O(N)

Espacio Auxiliar: O(1)
 

Publicación traducida automáticamente

Artículo escrito por souradeep 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 *