select two non overlapping segment such that sum of their length minimum. O(n) eg. [2,5], [4,6], [6,7]
ans-6 explanation 2 is overlapped with first and third but 1 and 3 is not ans-(5-2+1)+(7-6+1)=6 1<=n<=10^6 timeLimit-1 second
# | User | Rating |
---|---|---|
1 | jiangly | 4039 |
2 | tourist | 3841 |
3 | jqdai0815 | 3682 |
4 | ksun48 | 3590 |
5 | ecnerwala | 3542 |
6 | Benq | 3535 |
7 | orzdevinwang | 3526 |
8 | gamegame | 3477 |
9 | heuristica | 3357 |
10 | Radewoosh | 3355 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | -is-this-fft- | 165 |
3 | atcoder_official | 160 |
3 | Um_nik | 160 |
5 | djm03178 | 158 |
6 | Dominater069 | 156 |
7 | adamant | 153 |
8 | luogu_official | 152 |
9 | awoo | 151 |
10 | TheScrasse | 147 |
select two non overlapping segment such that sum of their length minimum. O(n) eg. [2,5], [4,6], [6,7]
ans-6 explanation 2 is overlapped with first and third but 1 and 3 is not ans-(5-2+1)+(7-6+1)=6 1<=n<=10^6 timeLimit-1 second
Name |
---|
What are the constraints on the values of $$$l$$$ and $$$r$$$ (the endpoints of an individual range)?
Anyways, independent of the constraints, I am posting my solution here.
Use a map container to store the minimum length of any range whose endpoint is on or before the key value.
In other words, $$$map[i]$$$ will denote the minimum length of a range with it's endpoint less than or equal to $$$i$$$. This map can be computed in $$$O(nlogn)$$$ time.
Now for every range $$$[l_i,r_i]$$$, find the key value less than $$$l_i$$$ in the map and pair up the minimum length obtained so with the length of the range number $$$i$$$. Just like you are searching for the best companion to this current range. Note that you don't need to search for ranges ahead of $$$r_i$$$ as they will ultimately be taken into consideration.
And your answer is the minimum sum you obtain while doing so for all ranges from $$$1$$$ to $$$n$$$.