Header Ad

HackerEarth Maximum Sum problem solution

In this HackerEarth Maximum Sum problem solution, 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.


HackerEarth Maximum Sum problem solution


HackerEarth Maximum Sum problem solution.

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

int main() {
int n;
cin >> n;
long long sum = 0;
int cnt = 0;
int mx = -2e9;
for(int i = 1; i <= n; i++) {
int x;
scanf("%d", &x);
if(x >= 0) sum += 1LL * x, cnt++;
mx = max(mx, x);
}
if(cnt) cout << sum << " " << cnt << endl;
else cout << mx << " " << 1 << endl;
return 0;
}

Second solution

#pragma GCC optimize("O3")
#include <bits/stdc++.h>

#define ll long long
#define ull unsigned long long
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define be begin()
#define en end()
#define le length()
#define sz size()

#define y0 sdkfaslhagaklsldk
#define y1 aasdfasdfasdf
#define yn askfhwqriuperikldjk
#define j1 assdgsdgasghsf
#define tm sdfjahlfasfh
#define lr asgasgash
#define norm asdfasdgasdgsd
#define have adsgagshdshfhds

#define eps 1e-6
#define pi 3.141592653589793

using namespace std;

template<class T> inline T gcd(T a, T b) { while(b) b ^= a ^= b ^= a %= b; return a; }
template<class T> inline T mod(T x) { if(x < 0) return -x; else return x; }

typedef vector<int> VII;
typedef pair<int, int> PII;
typedef pair<int, PII > PPII;
typedef vector< PII > VPII;

const int MOD = 1e9 + 7;
const int INF = 1e9;


int main(int argc, char* argv[]) {
if(argc == 2 or argc == 3) freopen(argv[1], "r", stdin);
if(argc == 3) freopen(argv[2], "w", stdout);
ios::sync_with_stdio(false);
int n, a, x = 0, mx = -INF;
ll s = 0;
assert(cin >> n);
assert(1 <= n and n <= 100000);
for (int i = 0; i < n; i++) {
assert(cin >> a);
assert(-INF <= a and a <= INF);
if (a >= 0) s += a, x++;
mx = max(a, mx);
}
assert(!(cin >> n));
if (x == 0) x = 1, s = mx;
cout << s << ' ' << x << endl;
return 0;
}


Post a Comment

0 Comments