-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaily120.cpp
More file actions
96 lines (78 loc) · 2.36 KB
/
Copy pathdaily120.cpp
File metadata and controls
96 lines (78 loc) · 2.36 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Solution 1 - FAIL
class Solution {
public:
long long minimumSteps(string s) {
auto nums = std::vector<char>{};
auto swaps = 0;
for (auto& c : s)
nums.push_back(c);
std::sort(nums.begin(), nums.end(), [&swaps](char a, char b) {
if (a < b)
++swaps;
return a < b;
});
return swaps;
}
};
// Solution 2 - FAIL
class Solution {
public:
long long minimumSteps(string s) {
/*
implementing quick/merge/bubble sorting?
sort array such that all 0s are to the left of 1s
start from the right
if index = 1, continue
if index = 0
while current index = 0
decrement index
increment zero counts
while current index = 1
increment one counts
total swaps = zero counts * one counts
*/
long long steps = 0;
int index = s.size() - 1;
while (index >= 0) {
if (s[index] == '1') {
index--;
continue;
}
long long zeroes = 0;
auto init_ind = index;
while (index >= 0 and s[index] == '0') {
zeroes++;
index--;
}
long long ones = 0;
while (index >= 0 and s[index] == '1') {
ones++;
index--;
}
// update string
s = s.substr(0, index + 1) + std::string(zeroes, '0') + std::string(ones, '1') + s.substr(init_ind + 1, s.size() - init_ind);
steps += zeroes * ones;
if (index > 0)
index = init_ind;
}
return steps;
}
};
// Solution 3
class Solution {
public:
long long minimumSteps(std::string s) {
long long steps = 0;
long long zeroes = 0; // Track how many '1's we have encountered
// Traverse from the end to the start of the string
for (int i = s.size() - 1; i >= 0; --i) {
if (s[i] == '0') {
zeroes++; // Count '0's
} else {
// For every '1', calculate the steps needed to move the current '1's past this '0'
steps += zeroes;
}
}
return steps;
}
};