すべての配列要素を最小限のコストで等しくする

サイズの配列が与えられた場合 n タスクは、すべての要素の値を次と等しくすることです。 最低コスト 。値を x から y に変更するコストは次のとおりです。 abs(x - y)。

例:  

入力: arr[] = [1 100 101]
出力 :100
説明: 最小限のコストですべての値を 100 に変更できます
|1 - 100| + |100 - 100| + |101 - 100| = 100

入力 : arr[] = [4 6]
出力 :2
説明: 最小コストですべての値を 5 に変更できます
|4 - 5| + |5 - 6| = 2

入力: arr[] = [5 5 5 5]
出力:
説明: すべての値はすでに等しいです。

[単純なアプローチ] 2 つのネストされたループの使用 - O(n^2) 時間と O(1) 空間

答えは常に配列値の 1 つになる可能性があることに注意してください。上記の 2 番目の例でも、同じコストで両方を 4 または両方を 6 にすることもできます。
この考え方は、配列内の各値を潜在的なターゲット値として考慮し、他のすべての要素をそのターゲット値に変換するための総コストを計算することです。考えられるすべての目標値をチェックすることで、全体的なコンバージョンコストが最小になる目標値を見つけることができます。

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  ));   

出力
100  

[想定されるアプローチ - 1] 二分探索の使用 - O(n Log (Range)) 時間と O(1) 空間

この考え方は、二分探索を利用して、すべての配列要素を変換する最適な値を効率的に見つけることです。総コスト関数は、可能な値の範囲全体で凸曲線 (最初は減少し、その後増加) を形成するため、二分探索を使用して、中間点のコストと中間点のコストから 1 を引いた値を比較することで、この曲線の最小点を見つけることができます。これにより、さらに探索する方向がわかります。

段階的なアプローチ:

  1. 配列内の最小値と最大値を見つけて検索範囲を設定します
  2. 最小値と最大値の間で二分探索を使用して、最適なターゲット値を見つけます。
  3. 試行値ごとに、すべての配列要素をその値に変換する総コストを計算します。
  4. 現在の中間点のコストと中間点から 1 を引いたコストを比較して、検索方向を決定します。
  5. 最小コストの構成が見つかるまで検索範囲を絞り続けます
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  ));   

出力
100 

[想定されるアプローチ - 2] ソートの使用 - O(n Log n) 時間と O(1) 空間

アイデアは、既存の配列要素の 1 つであるすべての要素を均等化する最適な値を見つけることです。最初に配列をソートし、次に潜在的なターゲット値として各要素を反復処理することにより、現在の位置の左右の要素の合計を効率的に追跡することにより、他のすべての要素をその値に変換するコストを計算します。

段階的なアプローチ:

  1. 配列をソートして要素を昇順に処理します。
  2. 潜在的なターゲット値としての要素ごとに、小さい要素を引き上げるコストと、大きい要素を下げるという 2 つのコストを計算します。
  3. 左右の合計を追跡して、反復ごとに一定時間でこれらのコストを効率的に計算します。
    • より小さい要素を増やすとコストが増加します: (現在の値 × より小さい要素の数) - (より小さい要素の合計)
    • より大きな要素のコスト削減: (より大きな要素の合計) - (現在の値 × より大きな要素の数)
  4. 現在のコストと最小コストを比較します。
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  ));   

出力
100 
クイズの作成