力扣刷题---502. IPO(大顶堆)

502. IPO

解题思路:将capital数组和profits数组融合成为一个结构体Node,先按照capital进行从小到大排序,如果capital大小一致则按照profits从大到小进行排序。创建一个大顶堆,按照profits进行排序,通过一个while循环不停将Node加入到大顶堆中去,每次取最大的元素进行相加,最后得到结果。

代码:

class Solution {
    private class Node{
        int x;
        int y;
        
        public Node(int x, int y){
            this.x = x;
            this.y = y;
        }
    }
    
    public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
        int len = profits.length;
        Node[] pc = new Node[len];
        for(int i=0;i<len;i++){
            pc[i] = new Node(profits[i], capital[i]);
        }
        //按照capital从小到大排序,相等则按照profits从大到小排序
        Arrays.sort(pc, (o1, o2) -> o1.y == o2.y ? o2.x - o1.x : o1.y - o2.y);
        //堆q按照profits从大到小排序
        PriorityQueue<Node> q = new PriorityQueue<>((o1, o2) -> o2.x - o1.x);
        int kk = 0;
        int idx = 0;
        while(kk < k){
            //大顶堆的堆顶元素或许都在不停的变换
            while(idx < len && pc[idx].y <= w){
                q.add(pc[idx++]);
            }
            if(q.isEmpty()){
                break;
            }
            kk++;
            w += q.poll().x;
        }
        return w;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值