Machen Sie alle Array-Elemente mit minimalen Kosten gleich

Gegeben ist ein Array mit einer Größe N Die Aufgabe besteht darin, den Wert aller Elemente gleich zu machen minimale Kosten . Die Kosten für die Änderung eines Werts von x nach y betragen abs(x - y).

Beispiele:  

Eingang: arr[] = [1 100 101]
Ausgabe : 100
Erläuterung: Wir können alle Werte mit minimalen Kosten auf 100 ändern
|1 - 100| + |100 - 100| + |101 - 100| = 100

Eingang : arr[] = [4 6]
Ausgabe : 2
Erläuterung: Wir können alle Werte mit minimalen Kosten auf 5 ändern
|4 - 5| + |5 - 6| = 2

Eingang: arr[] = [5 5 5 5]
Ausgabe:
Erläuterung: Alle Werte sind bereits gleich.

[Naiver Ansatz] Verwendung von 2 verschachtelten Schleifen – O(n^2) Zeit und O(1) Raum

Bitte beachten Sie, dass unsere Antwort immer einer der Array-Werte sein kann. Selbst im zweiten Beispiel oben können wir alternativ beide zu 4 oder beide zu 6 zum gleichen Preis herstellen.
Die Idee besteht darin, jeden Wert im Array als potenziellen Zielwert zu betrachten und dann die Gesamtkosten für die Konvertierung aller anderen Elemente in diesen Zielwert zu berechnen. Indem wir alle möglichen Zielwerte überprüfen, können wir denjenigen finden, der zu den minimalen Gesamtkosten für die Konvertierung führt.

C++
   // C++ program to Make all array    // elements equal with minimum cost   #include          using     namespace     std  ;   // Function which finds the minimum    // cost to make array elements equal   int     minCost  (  vector   <  int  >     &  arr  )     {      int     n     =     arr  .  size  ();      int     ans     =     INT_MAX  ;          // Try each element as the target value      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      int     currentCost     =     0  ;          // Calculate cost of making all       // elements equal to arr[i]      for     (  int     j     =     0  ;     j      <     n  ;     j  ++  )     {      currentCost     +=     abs  (  arr  [  j  ]     -     arr  [  i  ]);      }          // Update minimum cost if current cost is lower      ans     =     min  (  ans       currentCost  );      }          return     ans  ;   }   int     main  ()     {      vector   <  int  >     arr     =     {  1       100       101  };      cout      < <     minCost  (  arr  )      < <     endl  ;          return     0  ;   }   
Java
   // Java program to Make all array    // elements equal with minimum cost   import     java.util.*  ;   class   GfG     {      // Function which finds the minimum       // cost to make array elements equal      static     int     minCost  (  int  []     arr  )     {      int     n     =     arr  .  length  ;      int     ans     =     Integer  .  MAX_VALUE  ;      // Try each element as the target value      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      int     currentCost     =     0  ;      // Calculate cost of making all       // elements equal to arr[i]      for     (  int     j     =     0  ;     j      <     n  ;     j  ++  )     {      currentCost     +=     Math  .  abs  (  arr  [  j  ]     -     arr  [  i  ]  );      }      // Update minimum cost if current cost is lower      ans     =     Math  .  min  (  ans       currentCost  );      }      return     ans  ;      }      public     static     void     main  (  String  []     args  )     {      int  []     arr     =     {  1       100       101  };      System  .  out  .  println  (  minCost  (  arr  ));      }   }   
Python
   # Python program to Make all array    # elements equal with minimum cost   # Function which finds the minimum    # cost to make array elements equal   def   minCost  (  arr  ):   n   =   len  (  arr  )   ans   =   float  (  'inf'  )   # Try each element as the target value   for   i   in   range  (  n  ):   currentCost   =   0   # Calculate cost of making all    # elements equal to arr[i]   for   j   in   range  (  n  ):   currentCost   +=   abs  (  arr  [  j  ]   -   arr  [  i  ])   # Update minimum cost if current cost is lower   ans   =   min  (  ans     currentCost  )   return   ans   if   __name__   ==   '__main__'  :   arr   =   [  1     100     101  ]   print  (  minCost  (  arr  ))   
C#
   // C# program to Make all array    // elements equal with minimum cost   using     System  ;   class     GfG     {      // Function which finds the minimum       // cost to make array elements equal      static     int     minCost  (  int  []     arr  )     {      int     n     =     arr  .  Length  ;      int     ans     =     int  .  MaxValue  ;      // Try each element as the target value      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      int     currentCost     =     0  ;      // Calculate cost of making all       // elements equal to arr[i]      for     (  int     j     =     0  ;     j      <     n  ;     j  ++  )     {      currentCost     +=     Math  .  Abs  (  arr  [  j  ]     -     arr  [  i  ]);      }      // Update minimum cost if current cost is lower      ans     =     Math  .  Min  (  ans       currentCost  );      }      return     ans  ;      }      static     void     Main  ()     {      int  []     arr     =     {  1       100       101  };      Console  .  WriteLine  (  minCost  (  arr  ));      }   }   
JavaScript
   // JavaScript program to Make all array    // elements equal with minimum cost   // Function which finds the minimum    // cost to make array elements equal   function     minCost  (  arr  )     {      let     n     =     arr  .  length  ;      let     ans     =     Number  .  MAX_SAFE_INTEGER  ;      // Try each element as the target value      for     (  let     i     =     0  ;     i      <     n  ;     i  ++  )     {      let     currentCost     =     0  ;      // Calculate cost of making all       // elements equal to arr[i]      for     (  let     j     =     0  ;     j      <     n  ;     j  ++  )     {      currentCost     +=     Math  .  abs  (  arr  [  j  ]     -     arr  [  i  ]);      }      // Update minimum cost if current cost is lower      ans     =     Math  .  min  (  ans       currentCost  );      }      return     ans  ;   }   let     arr     =     [  1       100       101  ];   console  .  log  (  minCost  (  arr  ));   

Ausgabe
100  

[Erwarteter Ansatz – 1] Verwendung der binären Suche – O(n Log (Range)) Zeit und O(1) Raum

Die Idee besteht darin, die binäre Suche zu nutzen, um effizient den optimalen Wert zu finden, in den alle Array-Elemente konvertiert werden sollen. Da die Gesamtkostenfunktion eine konvexe Kurve (zuerst abnehmend, dann steigend) über den Bereich möglicher Werte bildet, können wir die binäre Suche verwenden, um den Minimalpunkt dieser Kurve zu lokalisieren, indem wir die Kosten in der Mitte mit den Kosten in der Mitte minus eins vergleichen, was uns sagt, in welche Richtung wir weiter suchen müssen.

Schritt-für-Schritt-Ansatz:

  1. Suchen Sie die Mindest- und Höchstwerte im Array, um den Suchbereich festzulegen
  2. Verwenden Sie die binäre Suche zwischen dem Minimal- und Maximalwert, um den optimalen Zielwert zu finden
  3. Berechnen Sie für jeden Testwert die Gesamtkosten für die Konvertierung aller Array-Elemente in diesen Wert
  4. Vergleichen Sie die Kosten zum aktuellen Mittelpunkt mit den Kosten zum Mittelpunkt minus eins, um die Suchrichtung zu bestimmen
  5. Grenzen Sie den Suchbereich weiter ein, bis Sie die Konfiguration mit den niedrigsten Kosten finden
C++
   // C++ program to Make all array    // elements equal with minimum cost   #include          using     namespace     std  ;   // Function to find the cost of changing   // array values to mid.   int     findCost  (  vector   <  int  >     &  arr       int     mid  )     {      int     n     =     arr  .  size  ();      int     ans     =     0  ;      for     (  int     i  =  0  ;     i   <  n  ;     i  ++  )     {      ans     +=     abs  (  arr  [  i  ]     -     mid  );      }      return     ans  ;   }   // Function which finds the minimum cost    // to make array elements equal.   int     minCost  (  vector   <  int  >     &  arr  )     {      int     n     =     arr  .  size  ();      int     mini     =     INT_MAX       maxi     =     INT_MIN  ;          // Find the minimum and maximum value.      for     (  int     i  =  0  ;     i   <  n  ;     i  ++  )     {      mini     =     min  (  mini       arr  [  i  ]);      maxi     =     max  (  maxi       arr  [  i  ]);      }          int     s     =     mini       e     =     maxi  ;      int     ans     =     INT_MAX  ;          while     (  s      <=     e  )     {      int     mid     =     s     +     (  e  -  s  )  /  2  ;          int     cost1     =     findCost  (  arr       mid  );      int     cost2     =     findCost  (  arr       mid  -1  );          if     (  cost1      <     cost2  )     {      ans     =     cost1  ;      s     =     mid     +     1  ;      }      else     {      e     =     mid     -     1  ;      }      }          return     ans  ;   }   int     main  ()     {      vector   <  int  >     arr     =     {  1       100       101  };      cout      < <     minCost  (  arr  );          return     0  ;   }   
Java
   // Java program to Make all array    // elements equal with minimum cost   import     java.util.*  ;   class   GfG     {      // Function to find the cost of changing      // array values to mid.      static     int     findCost  (  int  []     arr       int     mid  )     {      int     n     =     arr  .  length  ;      int     ans     =     0  ;      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      ans     +=     Math  .  abs  (  arr  [  i  ]     -     mid  );      }      return     ans  ;      }      // Function which finds the minimum cost       // to make array elements equal.      static     int     minCost  (  int  []     arr  )     {      int     n     =     arr  .  length  ;      int     mini     =     Integer  .  MAX_VALUE       maxi     =     Integer  .  MIN_VALUE  ;      // Find the minimum and maximum value.      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      mini     =     Math  .  min  (  mini       arr  [  i  ]  );      maxi     =     Math  .  max  (  maxi       arr  [  i  ]  );      }      int     s     =     mini       e     =     maxi  ;      int     ans     =     Integer  .  MAX_VALUE  ;      while     (  s      <=     e  )     {      int     mid     =     s     +     (  e     -     s  )     /     2  ;      int     cost1     =     findCost  (  arr       mid  );      int     cost2     =     findCost  (  arr       mid     -     1  );      if     (  cost1      <     cost2  )     {      ans     =     cost1  ;      s     =     mid     +     1  ;      }     else     {      e     =     mid     -     1  ;      }      }      return     ans  ;      }      public     static     void     main  (  String  []     args  )     {      int  []     arr     =     {  1       100       101  };      System  .  out  .  println  (  minCost  (  arr  ));      }   }   
Python
   # Python program to Make all array    # elements equal with minimum cost   # Function to find the cost of changing   # array values to mid.   def   findCost  (  arr     mid  ):   n   =   len  (  arr  )   ans   =   0   for   i   in   range  (  n  ):   ans   +=   abs  (  arr  [  i  ]   -   mid  )   return   ans   # Function which finds the minimum cost    # to make array elements equal.   def   minCost  (  arr  ):   n   =   len  (  arr  )   mini   =   float  (  'inf'  )   maxi   =   float  (  '-inf'  )   # Find the minimum and maximum value.   for   i   in   range  (  n  ):   mini   =   min  (  mini     arr  [  i  ])   maxi   =   max  (  maxi     arr  [  i  ])   s   =   mini   e   =   maxi   ans   =   float  (  'inf'  )   while   s    <=   e  :   mid   =   s   +   (  e   -   s  )   //   2   cost1   =   findCost  (  arr     mid  )   cost2   =   findCost  (  arr     mid   -   1  )   if   cost1    <   cost2  :   ans   =   cost1   s   =   mid   +   1   else  :   e   =   mid   -   1   return   ans   if   __name__   ==   '__main__'  :   arr   =   [  1     100     101  ]   print  (  minCost  (  arr  ))   
C#
   // C# program to Make all array    // elements equal with minimum cost   using     System  ;   class     GfG     {      // Function to find the cost of changing      // array values to mid.      static     int     findCost  (  int  []     arr       int     mid  )     {      int     n     =     arr  .  Length  ;      int     ans     =     0  ;      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      ans     +=     Math  .  Abs  (  arr  [  i  ]     -     mid  );      }      return     ans  ;      }      // Function which finds the minimum cost       // to make array elements equal.      static     int     minCost  (  int  []     arr  )     {      int     n     =     arr  .  Length  ;      int     mini     =     int  .  MaxValue       maxi     =     int  .  MinValue  ;      // Find the minimum and maximum value.      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      mini     =     Math  .  Min  (  mini       arr  [  i  ]);      maxi     =     Math  .  Max  (  maxi       arr  [  i  ]);      }      int     s     =     mini       e     =     maxi  ;      int     ans     =     int  .  MaxValue  ;      while     (  s      <=     e  )     {      int     mid     =     s     +     (  e     -     s  )     /     2  ;      int     cost1     =     findCost  (  arr       mid  );      int     cost2     =     findCost  (  arr       mid     -     1  );      if     (  cost1      <     cost2  )     {      ans     =     cost1  ;      s     =     mid     +     1  ;      }     else     {      e     =     mid     -     1  ;      }      }      return     ans  ;      }      static     void     Main  ()     {      int  []     arr     =     {  1       100       101  };      Console  .  WriteLine  (  minCost  (  arr  ));      }   }   
JavaScript
   // JavaScript program to Make all array    // elements equal with minimum cost   // Function to find the cost of changing   // array values to mid.   function     findCost  (  arr       mid  )     {      let     n     =     arr  .  length  ;      let     ans     =     0  ;      for     (  let     i     =     0  ;     i      <     n  ;     i  ++  )     {      ans     +=     Math  .  abs  (  arr  [  i  ]     -     mid  );      }      return     ans  ;   }   // Function which finds the minimum cost    // to make array elements equal.   function     minCost  (  arr  )     {      let     n     =     arr  .  length  ;      let     mini     =     Number  .  MAX_SAFE_INTEGER       maxi     =     Number  .  MIN_SAFE_INTEGER  ;      // Find the minimum and maximum value.      for     (  let     i     =     0  ;     i      <     n  ;     i  ++  )     {      mini     =     Math  .  min  (  mini       arr  [  i  ]);      maxi     =     Math  .  max  (  maxi       arr  [  i  ]);      }      let     s     =     mini       e     =     maxi  ;      let     ans     =     Number  .  MAX_SAFE_INTEGER  ;      while     (  s      <=     e  )     {      let     mid     =     Math  .  floor  (  s     +     (  e     -     s  )     /     2  );      let     cost1     =     findCost  (  arr       mid  );      let     cost2     =     findCost  (  arr       mid     -     1  );      if     (  cost1      <     cost2  )     {      ans     =     cost1  ;      s     =     mid     +     1  ;      }     else     {      e     =     mid     -     1  ;      }      }      return     ans  ;   }   let     arr     =     [  1       100       101  ];   console  .  log  (  minCost  (  arr  ));   

Ausgabe
100 

[Erwarteter Ansatz – 2] Verwenden der Sortierung – O(n Log n) Zeit und O(1) Raum

Die Idee besteht darin, den optimalen Wert zu finden, auf den alle Elemente angeglichen werden sollen, der eines der vorhandenen Array-Elemente sein muss. Indem wir zuerst das Array sortieren und dann jedes Element als potenziellen Zielwert durchlaufen, berechnen wir die Kosten für die Transformation aller anderen Elemente in diesen Wert, indem wir die Summe der Elemente links und rechts von der aktuellen Position effizient verfolgen.

Schritt-für-Schritt-Ansatz:

  1. Sortieren Sie das Array, um Elemente in aufsteigender Reihenfolge zu verarbeiten.
  2. Berechnen Sie für jedes Element als potenziellen Zielwert zwei Kosten: kleinere Elemente nach oben und größere Elemente nach unten bringen.
  3. Verfolgen Sie die linken und rechten Summen, um diese Kosten in konstanter Zeit pro Iteration effizient zu berechnen.
    • Kleinere Elemente erhöhen die Kosten: (aktueller Wert × Anzahl kleinerer Elemente) – (Summe kleinerer Elemente)
    • Kosten für größere Elemente senken: (Summe größerer Elemente) – (aktueller Wert × Anzahl größerer Elemente)
  4. Vergleichen Sie die aktuellen Kosten mit den Mindestkosten.
C++
   // C++ program to Make all array    // elements equal with minimum cost   #include          using     namespace     std  ;   // Function which finds the minimum cost    // to make array elements equal.   int     minCost  (  vector   <  int  >     &  arr  )     {      int     n     =     arr  .  size  ();      // Sort the array      sort  (  arr  .  begin  ()     arr  .  end  ());          // Variable to store sum of elements      // to the right side.      int     right     =     0  ;      for     (  int     i  =  0  ;     i   <  n  ;     i  ++  )     {      right     +=     arr  [  i  ];      }          int     ans     =     INT_MAX  ;      int     left     =     0  ;          for     (  int     i  =  0  ;     i   <  n  ;     i  ++  )     {          // Remove the current element from right sum.      right     -=     arr  [  i  ];          // Find cost of incrementing left side elements      int     leftCost     =     i     *     arr  [  i  ]     -     left  ;          // Find cost of decrementing right side elements.      int     rightCost     =     right     -     (  n  -1  -  i  )     *     arr  [  i  ];          ans     =     min  (  ans       leftCost     +     rightCost  );          // Add current value to left sum       left     +=     arr  [  i  ];      }          return     ans  ;   }   int     main  ()     {      vector   <  int  >     arr     =     {  1       100       101  };      cout      < <     minCost  (  arr  );          return     0  ;   }   
Java
   // Java program to Make all array    // elements equal with minimum cost   import     java.util.*  ;   class   GfG     {      // Function which finds the minimum cost       // to make array elements equal.      static     int     minCost  (  int  []     arr  )     {      int     n     =     arr  .  length  ;      // Sort the array      Arrays  .  sort  (  arr  );          // Variable to store sum of elements      // to the right side.      int     right     =     0  ;      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      right     +=     arr  [  i  ]  ;      }      int     ans     =     Integer  .  MAX_VALUE  ;      int     left     =     0  ;      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      // Remove the current element from right sum.      right     -=     arr  [  i  ]  ;      // Find cost of incrementing left side elements      int     leftCost     =     i     *     arr  [  i  ]     -     left  ;      // Find cost of decrementing right side elements.      int     rightCost     =     right     -     (  n     -     1     -     i  )     *     arr  [  i  ]  ;      ans     =     Math  .  min  (  ans       leftCost     +     rightCost  );      // Add current value to left sum       left     +=     arr  [  i  ]  ;      }      return     ans  ;      }      public     static     void     main  (  String  []     args  )     {      int  []     arr     =     {  1       100       101  };      System  .  out  .  println  (  minCost  (  arr  ));      }   }   
Python
   # Python program to Make all array    # elements equal with minimum cost   # Function which finds the minimum cost    # to make array elements equal.   def   minCost  (  arr  ):   n   =   len  (  arr  )   # Sort the array   arr  .  sort  ()   # Variable to store sum of elements   # to the right side.   right   =   sum  (  arr  )   ans   =   float  (  'inf'  )   left   =   0   for   i   in   range  (  n  ):   # Remove the current element from right sum.   right   -=   arr  [  i  ]   # Find cost of incrementing left side elements   leftCost   =   i   *   arr  [  i  ]   -   left   # Find cost of decrementing right side elements.   rightCost   =   right   -   (  n   -   1   -   i  )   *   arr  [  i  ]   ans   =   min  (  ans     leftCost   +   rightCost  )   # Add current value to left sum    left   +=   arr  [  i  ]   return   ans   if   __name__   ==   '__main__'  :   arr   =   [  1     100     101  ]   print  (  minCost  (  arr  ))   
C#
   // C# program to Make all array    // elements equal with minimum cost   using     System  ;   class     GfG     {      // Function which finds the minimum cost       // to make array elements equal.      static     int     minCost  (  int  []     arr  )     {      int     n     =     arr  .  Length  ;      // Sort the array      Array  .  Sort  (  arr  );      // Variable to store sum of elements      // to the right side.      int     right     =     0  ;      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      right     +=     arr  [  i  ];      }      int     ans     =     int  .  MaxValue  ;      int     left     =     0  ;      for     (  int     i     =     0  ;     i      <     n  ;     i  ++  )     {      // Remove the current element from right sum.      right     -=     arr  [  i  ];      // Find cost of incrementing left side elements      int     leftCost     =     i     *     arr  [  i  ]     -     left  ;      // Find cost of decrementing right side elements.      int     rightCost     =     right     -     (  n     -     1     -     i  )     *     arr  [  i  ];      ans     =     Math  .  Min  (  ans       leftCost     +     rightCost  );      // Add current value to left sum       left     +=     arr  [  i  ];      }      return     ans  ;      }      static     void     Main  ()     {      int  []     arr     =     {  1       100       101  };      Console  .  WriteLine  (  minCost  (  arr  ));      }   }   
JavaScript
   // JavaScript program to Make all array    // elements equal with minimum cost   // Function which finds the minimum cost    // to make array elements equal.   function     minCost  (  arr  )     {      let     n     =     arr  .  length  ;      // Sort the array      arr  .  sort  ((  a       b  )     =>     a     -     b  );      // Variable to store sum of elements      // to the right side.      let     right     =     0  ;      for     (  let     i     =     0  ;     i      <     n  ;     i  ++  )     {      right     +=     arr  [  i  ];      }      let     ans     =     Number  .  MAX_SAFE_INTEGER  ;      let     left     =     0  ;      for     (  let     i     =     0  ;     i      <     n  ;     i  ++  )     {      // Remove the current element from right sum.      right     -=     arr  [  i  ];      // Find cost of incrementing left side elements      let     leftCost     =     i     *     arr  [  i  ]     -     left  ;      // Find cost of decrementing right side elements.      let     rightCost     =     right     -     (  n     -     1     -     i  )     *     arr  [  i  ];      ans     =     Math  .  min  (  ans       leftCost     +     rightCost  );      // Add current value to left sum       left     +=     arr  [  i  ];      }      return     ans  ;   }   let     arr     =     [  1       100       101  ];   console  .  log  (  minCost  (  arr  ));   

Ausgabe
100 
Quiz erstellen