Minimum Subsequence in Non-Increasing Order

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. 

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[] = { 431098 };
        List<Integerarr = minSubsequence(nums);
        System.out.println(Arrays.asList(arr));
    }

    static List<IntegerminSubsequence(int[] nums) {
        // Sorting int Array in asc order
        Arrays.sort(nums);
        int sum = 0;

        // find the sum of array elements
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }
        int sum1 = 0;
        List<Integerres = 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<intminSubsequence(vector<int>& nums)
{
    //sort the array in decreasing order
       sort(nums.begin(),nums.end(),greater<int>());
        int sum=0;

    //find the sum of array elements
    for(int i=0;i<nums.size();i++)
        {
          sum+=nums[i];   
        }
     int sum1=0;
        vector<intres;
      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<intnums ={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