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 | 3898 |
2 | tourist | 3840 |
3 | orzdevinwang | 3706 |
4 | ksun48 | 3691 |
5 | jqdai0815 | 3682 |
6 | ecnerwala | 3525 |
7 | gamegame | 3477 |
8 | Benq | 3468 |
9 | Ormlis | 3381 |
10 | maroonrk | 3379 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | -is-this-fft- | 165 |
3 | Dominater069 | 160 |
4 | atcoder_official | 159 |
4 | Um_nik | 159 |
6 | djm03178 | 156 |
7 | adamant | 153 |
8 | luogu_official | 149 |
8 | awoo | 149 |
10 | TheScrasse | 146 |
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$$$.