_
_
_ _2014-01-10 22:46:51
Algorithms
_ _, 2014-01-10 22:46:51

How to find the maximum amount that can be obtained by adding an arbitrary non-breaking sequence of array elements?

The problem was the following - given an array of up to 200, 000 elements, the elements of which are integers in the range [-10000, 10000].
You need to find the maximum amount that can be obtained by adding an arbitrary inseparable sequence of elements of this array.
The type for the input data [2,-2,-5,2,2,-1,2,-3] will be 5 - the sum of the subarray [2,2,-1,2]
I'm not strong in algorithms, but I kind of felt true, though he forgot about the ridiculous boundary condition and did not have time to finish on time.
How would you go about solving this problem?
The condition also has a limitation on the execution time of the algorithm - no more than 2 seconds in their interpreter.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
_
_ _, 2014-01-10
@AMar4enko

Yes, I have become quite old - I missed such an elementary algorithm :)

S
Stanislav Lomadurov, 2014-01-11
@lomadurov

Solution in the forehead

var a = [], // Array
    i = 0, x,
    current = a[0] + a[1],
    max = current;

for (i = 0; i in a; i++) {
    current = a[i];
    for (x = i + 1; x in a; x++) {
        current = current + a[x];
        if (current > max) {
            max = current;
        }
    }
}
console.log('Result:', max);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question