博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 813. Largest Sum of Averages
阅读量:4620 次
发布时间:2019-06-09

本文共 1641 字,大约阅读时间需要 5 分钟。

原题链接在这里:

题目:

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.

Example:Input: A = [9,1,2,3,9]K = 3Output: 20Explanation: The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.We could have also partitioned A into [9, 1], [2], [3, 9], for example.That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.

Note:

  • 1 <= A.length <= 100.
  • 1 <= A[i] <= 10000.
  • 1 <= K <= A.length.
  • Answers within 10^-6 of the correct answer will be accepted as correct.

题解:

Let dp[k][i] denotes largest sum of averages of A up to index i in to k adjacent parts.

For j from k-1 to i, separate them into 2 sections, first k-1 parts from k-1 to j, second 1 part from j to i.

Then dp[k][i] = max(dp[k-1][j] + ave(j-i)).

可以降维.

Time Complexity: O(k*n^2). n = A.length.

Space: O(k*n). 

AC Java: 

1 class Solution { 2     public double largestSumOfAverages(int[] A, int K) { 3         if(A == null || A.length == 0){ 4             return 0; 5         } 6          7         int n = A.length; 8         double [] sum = new double[n+1]; 9         double [][] dp = new double[K+1][n+1];10         for(int i = 1; i<=n; i++){11             sum[i] = sum[i-1]+A[i-1];12             dp[1][i] = sum[i]/i;13         }14         15         for(int k = 2; k<=K; k++){16             for(int i = k; i<=n; i++){17                 for(int j = k-1; j

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11452314.html

你可能感兴趣的文章
mysql的csv数据导入与导出
查看>>
leetcode笔记:Pascal&#39;s Triangle
查看>>
ASP.NET性能优化之构建自定义文件缓存
查看>>
Shell——windows上写完放入linux的时候需要注意的问题
查看>>
65条常用的正则表达式
查看>>
Vscode断点调试PHP
查看>>
做前端要做的6大事
查看>>
LeetCode 813. Largest Sum of Averages
查看>>
vSphere、Hyper-V与XenServer 你选哪个?
查看>>
java.lang.UnsupportedClassVersionError
查看>>
实现接口必须要加注解@Override吗
查看>>
apicloud UISearchBar 使用方法
查看>>
【spring+websocket的使用】
查看>>
mongo二维数组操作
查看>>
localStorage之本地储存
查看>>
Archlinux 交换左Ctrl和Cap键
查看>>
java与数据结构(6)---java实现链栈
查看>>
#openstack故障处理汇总
查看>>
搜索旋转排序数组 II
查看>>
20、docker swarm
查看>>