-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 1769. Minimum Number of Operations to Move All Balls to Each B…
…ox (#683)
- Loading branch information
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
26 changes: 26 additions & 0 deletions
26
1769. Minimum Number of Operations to Move All Balls to Each Box
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
class Solution { | ||
public: | ||
vector<int> minOperations(string boxes) { | ||
int n = boxes.size(); | ||
vector<int> answer(n, 0); | ||
|
||
int ballsToLeft = 0, movesToLeft = 0; | ||
int ballsToRight = 0, movesToRight = 0; | ||
|
||
// Single pass: calculate moves from both left and right | ||
for (int i = 0; i < n; i++) { | ||
// Left pass | ||
answer[i] += movesToLeft; | ||
ballsToLeft += boxes[i] - '0'; | ||
movesToLeft += ballsToLeft; | ||
|
||
// Right pass | ||
int j = n - 1 - i; | ||
answer[j] += movesToRight; | ||
ballsToRight += boxes[j] - '0'; | ||
movesToRight += ballsToRight; | ||
} | ||
|
||
return answer; | ||
} | ||
}; |