Given the array nums
, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence.
If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array.
Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order.
Example 1:
Input: nums = [4,3,10,9,8] Output: [10,9] Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements.
Example 2:
Input: nums = [4,4,7,6,7] Output: [7,7,6] Explanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-decreasing order.
Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 100
这题描述的太复杂了,其实看透本质以后就很简单。题目说是要找出一个subsequnce,这里面所有的数字加起来要比不在subsequence里的数字加起来要大,并且要这个subsequence里数字最少和总和最大,这一听就是一堆奇怪的要求。但是本质上,就是无脑从大到小找这个数组里的数字,加起来看看有没有超过整个数组之和的一半,超过了就可以return了。
class Solution {
public List<Integer> minSubsequence(int[] nums) {
List<Integer> result = new ArrayList<>();
int sum = 0;
for (int i : nums) {
sum += i;
}
Arrays.sort(nums);
int partialSum = 0;
for (int i = nums.length - 1; i >= 0; i--) {
partialSum += nums[i];
result.add(nums[i]);
if (partialSum > sum / 2) {
break;
}
}
return result;
}
}