java - 平均数的最大总和

标签 java algorithm dynamic-programming

Problem Statement :

We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?

Note that our partition must use every number in A, and that scores are not necessarily integers.

我特别想了解集合生成背后的方法。考虑以下示例数组。

N= 5, Elements: [9,1,2,3,9,8]

k = 3

这些问题要求生成大小为 k 的步长。例如,我们可以有以下生成集(尽管实际集会更大)。

  • [9,1,2] & [3,9,8]
  • [9], [1,2,3], [9, 8]
  • [9,1,2], [3], [9, 8]

我试图理解没有内存的朴素递归解决方案。

问题:

I added logs to understand how these sets are generated. I am unable to understand how the sets [9,1,2] [3,9,8] will be generated using the following code snippet. More importantly how does it cover all possible setups upto size 3.

  public double largestSumOfAverages(int[] arr, int groupSize) {
    int[] sum = new int[arr.length];

    for (int i = 0; i < arr.length; i++) {
      sum[i] = arr[i] + (i > 0 ? sum[i - 1] : 0);
    }

    System.out.println(Arrays.toString(sum));
    return dfs(arr, groupSize, sum, arr.length, 0);
  }

  public double dfs(int[] arr, int groupSize, int[] sumToIthIndex, int right, int left) {
    if (groupSize == 1) {
      double avg1 = ((double) (sumToIthIndex[right - 1] - sumToIthIndex[left] + arr[left]) / (right
          - left));

      System.out.println(" dfs return :: " + left + " right:: " + right + "  :grpSize:: " + groupSize);
      return avg1;
    }
    double num = 0;
    for (int index = left; index + groupSize <= right; index++) {
      System.out.println(" dfs left:: " + index + " right:: " + right + "  :grpSize:: " + groupSize);
      num = Math.max(num,
          ((double) (sumToIthIndex[index] - sumToIthIndex[left] + arr[left]) / (index - left
              + 1)) + dfs(arr, groupSize - 1, sumToIthIndex, right,index + 1));
    }
    System.out.println("End");
    return num;
  }

最佳答案

您实际上不需要覆盖所有可能的设置,直到大小 3,因为您将总是想要使用您可用的最大组数(假设所有值都是正数)。

假设组大小为 k,并且您找到了 k-1 组的最佳答案。如果您选择这些组中的一个,从中获取最高值并将其放入自己的组中,那么您的分数会更高或相等,因此您的答案并不是真正的最佳答案。 (n 个数的平均值永远不会高于这些数中最大的一个)

关于java - 平均数的最大总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55483970/

相关文章:

algorithm - 动态规划递归公式

algorithm - 将一系列旋转表盘设置为给定序列的最少步骤

java - 如何在 ItestListener 中获取当前的类驱动程序

java - 我的前缀表达式计算器出现问题

arrays - 找到最接近给定数字的数组的三个元素之和的渐近最优方法

python - Django:使用过滤器随机查询一条记录的最快方法

algorithm - 在理解 "balanced 0-1 matrix"的动态编程方法方面需要帮助吗?

java - 使用编程资源注册的 Jersey 异步请求处理

java - ThreadPoolExecutor异常通知

CSS 十六进制到速记十六进制转换