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 n, long long a[]){long long sum = 0, cnt = 0;for (int i = 0; i < n; i++){if (a[i] >= 0){sum += a[i];cnt++;}}sort(a, a + n);if (cnt == 0)cout << a[n - 1] << " " << 1 << "\n";elsecout << sum << " " << cnt << "\n";}int main(){long long n = 5;long long a[n] = {1, 2, -4, -2, 3};maximumSum(n, a);return 0;}
No comments:
Post a Comment