Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Split Array With Same Average

$
0
0

题目描述:

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: trueExplanation: 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

 


Viewing all articles
Browse latest Browse all 559

Trending Articles