← Back to topics
Topic

MaxSum problem

M
Martin
this task seems really easy, but when I send my solution time limit is exceeded.
This is my solution:
#include <iostream>
using namespace std;
int main (void)
{
int n;
cin >>n;
int a[n+1];
int i=1,max=0,zbr=0;
while (i<=n)
{
cin >>a[i];
if (zbr<0) zbr=0;
zbr=zbr+a[i];
if (zbr>max) max=zbr;
++i;
}
if (max==0)
{
sort (a+1,a+(n+1));
max=a[n];
}
cout <<max<<endl;
system ("pause");
return 0;
}

if you know how to make this more simple please reply.
M
Martin
it still doesnt work...
k
karakondzula
Did you think about numbers less than zero?
What do you get for this:
4
-1
-2
-3
-4

solution is -1.
D
Daniel93
I think there aren't such casses , cause my code works wihout it.But as you see in his code he has thinked about. Try to use long long int, that was the problem when I've sent it.

And another thing. Don't use "cin" its much slower than "scanf". ( that's the reason for the TLE )
l
lifetime
#include <iostream>
#include <cstdlib>
using namespace std;
int main (void)
{
int n;
cin >>n;
int *a = new int[n+1];
int i=1,max=0,zbr=0;
while (i<=n)
{
cin >>a[i];
if (zbr<0) zbr=0;
zbr=zbr+a[i];
if (zbr>max) max=zbr;
++i;
}
if (max==0)
{
//sort (a+1,a+(n+1));
max=a[n];
}
cout <<max<<endl;
system ("pause");
return 0;
}
M
Martin
it doesn't work...
g
goran_f2
reverse the order of lines 14 and 15 and DON'T SORT!
M
Martin
now it works, thanks.

I have another question.
when i send my code it all works, but when i test it on my own it doesn't.
everything worked when i used "cin" and "cout", but when i started using "scanf" and "printf" it wont work. In the first line I enter "6" but it doesn't give me a result after seventh line. I have to continue entering numbers until it crashes. (after entering more then 10 numbers)
I don't understand this because when i send it as a answer here, everything works.
g
gigac
Hello.
Will someone explain what this task wants from the solvers.
I try to solve it, and for the examples I got correct answers, but when it compiles give me only 3 correct :S