数组分割:左边子数组之和大于右边子数组

        

/*Given an integer array, divide the array into 2 subsets A and B while respecting the following conditions :

*  The intersection of A and B is null.
* The union A and B is equal to the original array.
* The number of elements in subset A is minimal.
* The sum of A's elements is greater than the sum of B's elements.

 
Return the subset A in increasing order where the sum of A's elements is greater than the sum of B's elements. 
If more than one subset exists, return the one with the maximal sum.
 
 
Example
n = 5
arr = [3, 7, 5, 6, 2]
 
The 2 subsets in arr that satisfy the conditions for A are [5, 7] and  [6, 7] :

* A is minimal (size 2)
* Sum(A) = (5 + 7) = 12 > Sum(B) = (2 + 3 + 6) = 11
* Sum(A) = (6 + 7) = 13 > Sum(B) = (2 + 3 + 5) = 10
* The intersection of A and B is null and their union is equal to arr.
* The subset A where the sum of its elements is maximal is [6, 7].

 
Function Description
Complete the subsetA function in the editor below.
 
subsetA has the following parameter(s):
 int arr[]: an integer array
Returns:
 int[] : an integer array with the values of subset A.
 
Constraints

* 1 ≤ n ≤ 105

*/
#include "stdio.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <memory>
#include <map>
#include <unordered_set>
#include <unordered_map>
using namespace std;

vector<int> findMiniBiggerA(vector<int> orgArray) {
    sort(orgArray.begin(), orgArray.end(), [](const int &a, const int &b){ return a>b;});
    
    unordered_map<int, int> upToNowSum;
    int i=0;
    int sum = 0;
    for(auto in: orgArray) {
        cout<<"Sorted Array is:"<<in<<endl;
        sum += in;
        upToNowSum[i] =sum;
        i++;
    }

    vector<int> subSetA;

    for( int j=0; j<orgArray.size();j++  ) {
        if( 2*upToNowSum[j] >sum ) {
            int m=j;
            for(int i=0; i<=m; i++) {
                subSetA.push_back(orgArray[i]);
            }
            break;
        }
    }

      for(auto in: subSetA) {
        cout<<"Sub Array is:"<<in<<endl;;
    }
    return subSetA;

}


int main(int argc, char **argv){
    vector<int> orgArrayTest1= { 3, 7, 5, 6, 2};
    vector<int> subArrayTest1;
    subArrayTest1 = findMiniBiggerA(orgArrayTest1);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值