2022-01-01:给定int[][] meetings,比如 { {66, 70} 0号会议截止时间66,获得收益70 {25, 90} 1号会议截止时间25,获得收益90 {50, 30} 2号会议截止时间50,获得收益30 } 一开始的时间是0,任何会议都持续10的时间,但是一个会议一定要在该会议截止时间之前开始, 只有一个会议室,任何会议不能共用会议室,一旦一个会议被正确安排,将获得这个会议的收益。 请返回最大的收益。

答案2022-01-01:

按截止时间从小到大排序,小根堆。

代码用golang编写。代码如下:

package main

import (
    "fmt"
    "sort"
)

func main() {
    meetings := [][]int{{6, 20}, {9, 50}, {13, 42}}
    ret := maxScore1(meetings)
    fmt.Println(ret)
    ret = maxScore2(meetings)
    fmt.Println(ret)
}

func maxScore1(meetings [][]int) int {
    //Arrays.sort(meetings, (a, b) -> a[0] - b[0]);
    sort.Slice(meetings, func(i, j int) bool {
        return meetings[i][0] < meetings[j][0]
    })
    //int[][] path = new int[meetings.length][];
    path0 := make([][]int, len(meetings))
    for i := 0; i < len(meetings); i++ {
        path0[i] = make([]int, 2)
    }
    size := 0
    return process1(meetings, 0, path0, size)
}

func process1(meetings [][]int, index int, path0 [][]int, size int) int {
    if index == len(meetings) {
        time := 0
        ans := 0
        for i := 0; i < size; i++ {
            if time+10 <= path0[i][0] {
                ans += path0[i][1]
                time += 10
            } else {
                return 0
            }
        }
        return ans
    }
    p1 := process1(meetings, index+1, path0, size)
    path0[size] = meetings[index]
    p2 := process1(meetings, index+1, path0, size+1)
    // path[size] = null;
    return getMax(p1, p2)
}

func getMax(a, b int) int {
    if a > b {
        return a
    } else {
        return b
    }
}

func maxScore2(meetings [][]int) int {
    sort.Slice(meetings, func(i, j int) bool {
        return meetings[i][0] < meetings[j][0]
    })
    heap := make([]int, 0)
    time := 0
    // 已经把所有会议,按照截止时间,从小到大,排序了!
    // 截止时间一样的,谁排前谁排后,无所谓
    for i := 0; i < len(meetings); i++ {
        if time+10 <= meetings[i][0] {
            heap = append(heap, meetings[i][1])
            sort.Slice(heap, func(i, j int) bool {
                return heap[i] < heap[j]
            })
            time += 10
        } else {
            if len(heap) > 0 && heap[0] < meetings[i][1] {
                heap[0] = meetings[i][1]
                sort.Slice(heap, func(i, j int) bool {
                    return heap[i] < heap[j]
                })
            }
        }
    }
    ans := 0
    for len(heap) > 0 {
        ans += heap[0]
        heap = heap[1:]
        sort.Slice(heap, func(i, j int) bool {
            return heap[i] < heap[j]
        })
    }
    return ans
}

执行结果如下: 图片


左神java代码