[Hacker Rank] Cutting Boards

Cutting Boards

  • Time : O(nlogn + mlogm)
  • Space : O(1)
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
int boardCutting(vector<int> cy, vector<int> cx) {
long long res = 0, x = 1, y = 1, mod = 1e9 + 7;
sort(begin(cy), end(cy));
sort(begin(cx), end(cx));
while(!cy.empty() and !cx.empty()) {
long long ycost = x * cy.back(), xcost = y * cx.back();
if(cy.back() > cx.back()) {
res = (res + ycost) % mod;
cy.pop_back();
y++;
} else {
res = (res + xcost) % mod;
cx.pop_back();
x++;
}
}
while(!cy.empty()) {
long long ycost = x * cy.back();
res = (res + ycost) % mod;
cy.pop_back();
y++;
}
while(!cx.empty()) {
long long xcost = y * cx.back();
res = (res + xcost) % mod;
cx.pop_back();
x++;
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/13/PS/HackerRank/board-cutting/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.