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 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 151 |
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$$$.