简体   繁体   中英

How to pick one number from each sorted list so that the difference between the minimum and maximum is as small as possible? [closed]

Consider there are k-lists with numbers in an increasing order. Select one number from each list such that the difference between the highest number and lowest number in the output list is minimum:

list 1-1,3,5,9,10
list 2-2,4,6,8
list 3-7,11,12,13

The output should be 5,6,7.

5 is selected from list-l and 6 from list-2 and 7 from list-3

As the difference between highest and lowest number in that list is 2 that is 7-5 consider there are k-lists.

i can solve this in O(N*LogK) , here N is the total number of numbers in the k lists.

1, maintain a pointer for each list, starting from 0.

2, regard current pointers as the numbers you choose, update the answer.

3, select the one with minimum number and increase it by one(as long as it didn't reach the end of that list), if possible, back to step 2, otherwise terminate.

in step 2, and step 3, use heap to maintain the minimum number and maximum, which reduce the time from O(K) to O(LogK) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM