Advertisement
imashutosh51

Minimum Number of Operations to Move All Balls to Each Box

Aug 30th, 2022 (edited)
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. /*
  2. Method:-1
  3. class Solution {
  4. public:
  5.     vector<int> minOperations(string boxes) {
  6.         vector <int> left,right;
  7.         int prev_val=0,prev_count=0;
  8.         for(int i=0;i<boxes.size();i++){
  9.             left.push_back(prev_val+prev_count);
  10.             prev_val=prev_val+prev_count;
  11.             if(boxes[i]=='1') prev_count++;
  12.         }
  13.         prev_val=0;
  14.         prev_count=0;
  15.         for(int i=boxes.size()-1;i>=0;i--){
  16.             left[i]+=prev_val+prev_count;
  17.             prev_val=prev_val+prev_count;
  18.             if(boxes[i]=='1') prev_count++;
  19.         }
  20.         return left;
  21.     }
  22. };
  23. */
  24. /*
  25.    Leetcode:
  26.    First to bring all the balls to 0th position will be the sum of all the balls indexes.
  27.    Assume at ith position,We need n opeation to shift all balls into ith box.
  28.    Let's assume we know all the balls in the left and right of ith position
  29.    as per the initial state.
  30.    so,in case of (i+1)th box,all the balls in the left of (i+1)th box will
  31.    move one more box than the ith box and all the balls in the right of (i+1)th
  32.    including (i+1)th box will move one less boxes.
  33.    so,
  34.    arr[i+1]=arr[i]+left-right(including current box)
  35. */
  36.  
  37. class Solution {
  38. public:
  39.     vector<int> minOperations(string boxes) {
  40.         vector <int> ans;
  41.         int cur=0,right=0,left=0;
  42.         for(int i=1;i<boxes.size();i++){
  43.             if(boxes[i]=='1'){ cur+=i; right++;}
  44.         }
  45.         if(boxes[0]=='1') left++;
  46.         ans.push_back(cur);
  47.         for(int i=1;i<boxes.size();i++){
  48.             ans.push_back(ans.back()-right+left);
  49.             if(boxes[i]=='1'){ left++; right--;}
  50.         }
  51.         return ans;
  52.     }
  53. };
  54.  
  55. #Python
  56. class Solution:
  57.     def minOperations(self, boxes: str) -> List[int]:
  58.         right=0
  59.         ops=0
  60.         for i in range(1,len(boxes)):
  61.             ops+=i if boxes[i]=='1' else 0
  62.             right+=1 if boxes[i]=='1' else 0
  63.         left=1 if boxes[0]=='1' else 0
  64.         ans=[ops]
  65.         for i in range(1,len(boxes)):
  66.             ans.append(ans[i-1]+left-right)
  67.             right-=1 if boxes[i]=='1' else 0
  68.             left+=1 if boxes[i]=='1' else 0
  69.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement