Javascript:k次运算后求最小和

问题描述

对数组进行k次操作,以便每次将最大值除以2并向上舍入。经过这k次操作后,我需要找到其最小值。 k,数组num> 1中的所有数字。方法minSum接收一个名为num和整数k的数组。适用于我的具有很差的时间复杂度的原始Python代码是:

function minSum(arr,k) {
    // Write your code here
let sum = 0; 
    while(k !==0){

       
        let max = Math.max(...arr)
        let index = arr.indexOf(max);
         
        max = Math.ceil(max/2);
        arr[index] = max;
        
        k--;
    }
    sum =  arr.reduce((a,b) => a + b,0);
        console.log(sum);
    return sum;
}

与python有关的类似问题在这里More efficient method of finding minimum sum after k operations

但与Java语言无关。

enter image description here

解决方法

以下是步骤(根据您在更改JavaScript之前的第一个需求使用Java):

    1. 使用最大堆(PriorityQueue的顺序相反),因此最大堆将位于顶部。
    1. 对于k次迭代:将元素放在顶部(poll()),进行操作,然后将其再次添加到最大堆中。
    1. 最后,求和。
    public static int minSumJava_using_pqueue(int arr[],int k)
    {
        PriorityQueue<Integer> pq = new PriorityQueue<>(10,Collections.reverseOrder());

        for (int val : arr) {
            pq.add(val);
        }

        int new_val;
        for(int i =0; i<k; i++)
        {
            new_val = pq.poll();
            new_val = (int) Math.ceil(new_val/2.0);
            pq.add(new_val);
        }

        int sum = 0;
        for (Integer val: pq) {
            sum += val;
        }
        
        return sum;
    }

检查源代码:

    public static void main(String[] args)
    {
        int k = 4;
        int arr[] = {10,20,7};
        int result = minSumJava_using_pqueue(arr,k);
        System.out.println("min sum = "+ result);
    }

结果确实与您的示例相同:

min sum = 14

注意:您可以使用JavaScript或任何其他编程语言做完全相同的事情

,
const minSum = (arr,k) => {
  let newArr = arr
  while (k--) {
    let max;
    let newValue;
    let replacingIndex;
    max = Math.max.apply(Math,newArr);
    newValue = Math.ceil(max / 2);
    replacingIndex = newArr.findIndex((value) => value === max);
    newArr[replacingIndex] = newValue;
  }
  return newArr.reduce((a,b) => {a + b})
}