-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmin_operations.cpp
More file actions
61 lines (56 loc) · 1.5 KB
/
min_operations.cpp
File metadata and controls
61 lines (56 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* =====================================================================================
*
* Filename: min_operations.cpp
*
* Description: 1769. Minimum Number of Operations to Move All Balls to Each Box
*
* Version: 1.0
* Created: 05/30/2025 07:16:52
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
class Solution {
public:
std::vector<int> minOperations(std::string boxes) {
int left_balls = 0;
int left_moves = 0;
int right_balls = 0;
int right_moves = 0;
std::vector<int> answer(boxes.size(), 0);
for (int i = boxes.size() - 1; i >= 0; i--) {
right_moves += right_balls;
if (boxes[i] == '1') {
right_balls++;
}
}
for (int i = 0; i < boxes.size(); i++) {
answer[i] = left_moves + right_moves;
if (boxes[i] == '1') {
left_balls++;
right_balls--;
}
left_moves += left_balls;
right_moves -= right_balls;
}
return answer;
}
};
TEST(Solution, minOperations) {
std::vector<std::pair<std::string, std::vector<int>>> cases = {
{"110", {1, 1, 3}},
{"001011", {11, 8, 5, 4, 3, 4}},
};
for (auto& [boxes, answer] : cases) {
EXPECT_THAT(Solution().minOperations(boxes), testing::ElementsAreArray(answer));
}
}