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 | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 166 |
2 | maomao90 | 163 |
2 | Um_nik | 163 |
4 | atcoder_official | 161 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | nor | 153 |
9 | Dominater069 | 153 |
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$$$.