Advertisement
imashutosh51

Removing Minimum Number of Magic Beans

Jun 14th, 2023 (edited)
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. /*
  2. If we choose to make x bags empty,we should choose the x bags with the least amount
  3. of beans.so better to sort the array.so we need to find the m which will be out beans
  4. for non-empty bags.so possibility of m can be numbers in array because we can only
  5. reduce the beans,can't add any beans.so after sorting,we can make empty ith bag and make
  6. all bag after i to i+1th bean,in this way all arr[i] will be m once.
  7.  
  8.  
  9.  
  10. */
  11. long long _min(long long a,long long b){
  12.     if(a<b) return a;
  13.     return b;
  14. }
  15. class Solution {
  16. public:
  17.     long long minimumRemoval(vector<int>& beans) {
  18.         sort(beans.begin(),beans.end());
  19.         long long sum=0,prev_sum=0;
  20.         for(auto itr:beans) sum+=itr;
  21.         long long ans=sum;  //This is must because you can't put INT_MAX here because if k=0,then answer will be sum not INT_MAX.
  22.         for(long long int i=0;i<beans.size();i++){
  23.             long long temp=prev_sum+sum-prev_sum-(beans.size()-i)*beans[i];
  24.             ans=_min(ans, temp );
  25.             prev_sum+=beans[i];
  26.         }
  27.         return ans;
  28.     }
  29. };
  30.  
  31. #Python
  32. class Solution:
  33.     def minimumRemoval(self, beans: List[int]) -> int:
  34.         arr=sorted(beans)
  35.         total=sum(beans)
  36.         ans=total
  37.         n=len(beans)
  38.         for i in range(len(arr)):
  39.             ans=min(ans,total-((n-i)*arr[i]))
  40.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement