HackerRank/Algorithm/Dynamic Programming/The Maximum Subarray

Problem Summary

Given an array A with N integers, find the maximum sum of a

  1. Continguous subarray.
  2. Not necessarily contiguous subarray.

Empty subarrays or subsequences should not be considered.

Solution

Two subproblems both can be solved with dynamic programming and greedy.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <climits>
using namespace std;
int main()
{
int T,n;
scanf("%d",&T);
while(T)
{
T--;
scanf("%d",&n);
int d,sum=0,mins=0,ans1=-1e9,ans2=0,maxd=-1e9;
for(int i=1;i<=n;i++)
{
scanf("%d",&d);
if(d>0) ans2+=d;
if(d>maxd) maxd=d;
sum += d;
if(sum-mins>ans1) ans1 = sum-mins;
if(sum<mins) mins=sum;
}
if(maxd<0) ans2 = maxd;
printf("%d %d\n",ans1,ans2);
}
return 0;
}