Advertisement
imashutosh51

Minimum Number of Operations to Move All Balls to Each Box

Aug 30th, 2022 (edited)
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 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.    Assume at ith position,We need n opeation to shift all balls into ith box.
  27.    Let's assume we know all the balls in the left and right of ith position
  28.    as per the initial state.
  29.    so,in case of (i+1)th box,all the balls in the left of (i+1)th box will
  30.    move one more box than the ith box and all the balls in the right of (i+1)th
  31.    including (i+1)th box will move one less boxes.
  32.    so,
  33.    arr[i+1]=arr[i]+left-right(including current box)
  34. */
  35.  
  36. class Solution {
  37. public:
  38.     vector<int> minOperations(string boxes) {
  39.         vector <int> ans;
  40.         int cur=0,right=0,left=0;
  41.         for(int i=1;i<boxes.size();i++){
  42.             if(boxes[i]=='1'){ cur+=i; right++;}
  43.         }
  44.         if(boxes[0]=='1') left++;
  45.         ans.push_back(cur);
  46.         for(int i=1;i<boxes.size();i++){
  47.             ans.push_back(ans.back()-right+left);
  48.             if(boxes[i]=='1'){ left++; right--;}
  49.         }
  50.         return ans;
  51.     }
  52. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement