-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChangingString.hpp
49 lines (46 loc) · 1.4 KB
/
ChangingString.hpp
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
#include <iostream>
#include <vector>
#include <math.h>
#include <string>
using namespace std;
class ChangingString
{
public:
int distance(string A, string B, int K) {
vector<int> distances;
int diff = 0;
int total = 0;
int currentMax = -1;
int maxPosition = 0;
// Iterate both strings and store distance between each corresponding letters in 'distances'
for (int i=0; i<A.length(); i++) {
diff = abs(A[i] - B[i]);
distances.push_back(diff);
// Calculate total distance of original array
total += diff;
}
// Deduct K first maximum distances from total
for (int k=0; k<K; k++) {
// Find currentMax
for (int i=0; i<distances.size(); i++) {
if (distances[i] > currentMax) {
currentMax = distances[i];
maxPosition = i;
}
}
if (currentMax == 0) {
// Increment by 1 if value to be deducted is 0
total++;
} else {
// Otherwise, deduct the maximum value
total = total - currentMax;
}
// mark as deducted
distances[maxPosition] = -1;
// reset currentMax
currentMax = -1;
}
// Return minimum distance
return total;
}
};