[Codewars] Sum of Intervals

Sum of Intervals

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <vector>
#include <utility>
using namespace std;
int sum_intervals(std::vector<std::pair<int, int>> A) {
sort(begin(A), end(A));
long long res = 0, le = -2147483648ll, ri = -2147483648ll;
for(auto [l,r] : A) {
if(l < ri) ri = max(ri, r * 1ll);
else {
res += ri - le;
le = l, ri = r;
}
}
res += ri - le;
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/10/PS/Codewars/sum-of-intervals/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.