美文网首页
6022 Minimum Operations to Halve

6022 Minimum Operations to Halve

作者: 进击的程序员97 | 来源:发表于2022-03-19 23:43 被阅读0次

just greedy, every time choose max element currently, and judge the sum is less than its half or not

here is my code

class Solution {

    public int halveArray(int[] nums) {

        PriorityQueue<Double> q = new PriorityQueue<>((a, b) -> b > a ? 1 : b == a ? 0 : -1);

        double sum = 0;

        for (int a : nums) {

            sum += a;

            q.add((double)a);

        }

        double target = sum / 2;

        int cnt = 0;

        while (!q.isEmpty() && sum > target) {

            double max = q.poll();

            max /= 2;

            sum -= max;

            System.out.println(sum + "," + max);

            q.add(max);

            cnt++;

        }

        return cnt;

    }

}

相关文章

网友评论

      本文标题:6022 Minimum Operations to Halve

      本文链接:https://www.haomeiwen.com/subject/lafodrtx.html