Given the array
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.
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.
Example 1:
Input: nums = {4,3,10,9,8}
Output: arr={10,9}
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class MinSubseqIncOrder {public static void main(String[] args) {int nums[] = { 4, 3, 10, 9, 8 };List<Integer> arr = minSubsequence(nums);System.out.println(Arrays.asList(arr));}static List<Integer> minSubsequence(int[] nums) {// Sorting int Array in asc orderArrays.sort(nums);int sum = 0;// find the sum of array elementsfor (int i = 0; i < nums.length; i++) {sum += nums[i];}int sum1 = 0;List<Integer> res = new ArrayList<Integer>();for (int i = nums.length - 1; i >= 0; i--) {sum1 += nums[i];res.add(nums[i]);if (sum1 > sum / 2) {break;}}return res;}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> minSubsequence(vector<int>& nums){//sort the array in decreasing ordersort(nums.begin(),nums.end(),greater<int>());int sum=0;//find the sum of array elementsfor(int i=0;i<nums.size();i++){sum+=nums[i];}int sum1=0;vector<int> res;for(int i=0;i<nums.size();i++){sum1+=nums[i];res.push_back(nums[i]);if(sum1>sum/2){break;}}return res;}int main(){vector<int> nums ={4,3,10,9,8};vector<int > arr=minSubsequence(nums);for(int i=0;i<arr.size();i++)cout<<arr[i]<<" ";return 0;}
No comments:
Post a Comment