题目描述:
LeetCode 805. Split Array With Same Average
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example : Input: [1,2,3,4,5,6,7,8] Output: true Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
- The length of
A
will be in the range [1, 30]. A[i]
will be in the range of[0, 10000]
.
题目大意:
给定整数数组A,求是否可以将A分成平均数相等的两个非空子数组。
解题思路:
动态规划(Dynamic Programming)
Python代码:
class Solution(object):
def splitArraySameAverage(self, A):
"""
:type A: List[int]
:rtype: bool
"""
A.sort(reverse = True)
dp = {0 : 0}
size, total = len(A), sum(A)
for a in A:
for k in sorted(dp.keys(), reverse = True):
dp[k + a] = dp[k] + 1
k += a
v = dp[k]
if v and size - v and k * (size - v) == (total - k) * v:
return True
return False
本文链接:http://bookshadow.com/weblog/2018/03/27/leetcode-split-array-with-same-average/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。