Skip to content

Instantly share code, notes, and snippets.

@ayushgoel
Created January 8, 2016 20:44
Show Gist options
  • Save ayushgoel/dd45663744652724fc7b to your computer and use it in GitHub Desktop.
Save ayushgoel/dd45663744652724fc7b to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
long max(long a, long b) {
return (a > b) ? a : b;
}
long get_contiguous_solution(int n, int *a) {
long max_so_far = a[0];
long max_ending_here = a[0];
for (int i = 1; i < n; ++i) {
max_ending_here = max(a[i], max_ending_here + a[i]);
max_so_far = max(max_so_far, max_ending_here);
}
return max_so_far;
}
long get_non_contiguous_solution(int n, int *a) {
long sum = 0;
long max_a = a[0];
int all_negatives = 1;
for (int i = 0; i < n; ++i) {
max_a = max(max_a, a[i]);
if (a[i] > 0) {
all_negatives = 0;
sum += a[i];
}
}
if (all_negatives) {
return max_a;
}
return sum;
}
void solve_case() {
int n, a[100005];
scanf("%d", &n);
for (int i = 0; i < n; ++i)
{
scanf("%d", &a[i]);
}
long c_sol = get_contiguous_solution(n, a);
long nc_sol = get_non_contiguous_solution(n, a);
printf("%ld %ld\n", c_sol, nc_sol);
}
int main() {
int t = 0;
scanf("%d", &t);
for (int i = 0; i < t; ++i)
{
solve_case();
}
return 0;
}
@Kiran-Oleti
Copy link

test cases are failing brother

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment