Maximum Sum

You are given an array of integers A, you need to find the maximum sum that can be obtained by picking some non-empty subset of the array. If there are many such non-empty subsets, choose the one with the maximum number of elements. Print the maximum sum and the number of elements in the chosen subset.

Example:

Input:  n = 5, a = [1, 2, -4, -2, 3]
Output: 6 3

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void maximumSum(long long nlong long a[])
{
    long long sum = 0cnt = 0;
    for (int i = 0i < ni++)
    {
        if (a[i] >= 0)
        {
            sum += a[i];
            cnt++;
        }
    }
    sort(aa + n);
    if (cnt == 0)
        cout << a[n - 1<< " " << 1 << "\n";
    else
        cout << sum << " " << cnt << "\n";
}
int main()
{
    long long n = 5;

    long long a[n] = {12, -4, -23};

    maximumSum(na);

    return 0;
}


No comments:

Post a Comment