Algorithm to find the maximum sum in a sequence of overlapping intervals

前端 未结 6 919
南旧
南旧 2020-11-30 19:33

The problem I am trying to solve has a list of intervals on the number line, each with a pre-defined score. I need to return the maximum possible total score.

The c

6条回答
  •  一生所求
    2020-11-30 20:35

    First of all, I think the maximum is 59, not 55. If you choose intervals [0-5],[8-21], and [25,30], you get 15+19+25=59. You can use some sort of dynamic programming to handle this.

    First, you sort all the intervals by their starting point, then iterate from end to start. For each item in list, you choose the maximum sum from that point to the last as max(S[i]+S[j], S[i+1]), where i is the item you are on, j is the item that is the first non-overlapping entry following your item (that is, the first item whose start is larger than the current item's end). To speed up the algorithm, you want to store the maximum partial sum S[j] for each element.

    To clarify, let me solve your example according to this. First, sort your intervals:

     1:  0- 5 -  15
     2:  4- 9 -  18
     3:  8-21 -  19
     4: 10-15 -  12
     5: 25-30 -  25
    

    So,

     S[5] = 25
     S[4] = max(12+S[5], 25)=37
     S[3] = max(19+S[5], S[4])=max(19+25,37)=44
     S[2] = max(18+S[4], S[3])=max(18+37,44)=55
     S[1] = max(15+S[3], S[2])=max(15+44, 55)=59
    

    This is an adaptation of the algorithm in this post, but unfortunately, doesn't have the nice O(n) running time. A degenerate list where each entry overlaps the next would cause it to be O(n^2).

提交回复
热议问题