# Solution to Max-Slice-Sum by codility

26 Jan

Question Name: MaxSliceSum

The classic maximum subarray problem. It should be the very first question in this lesson.

### 14 Replies to “Solution to Max-Slice-Sum by codility”

1. Karol says:

Here is my solution, somewhat similar ðŸ™‚ Python 100/100

• Sheng says:

Classic question and classic solution ðŸ™‚

• zaid says:

• Sheng says:

Why? It should be right.

PS: max_ending = max(0, max_ending + A[i]) is executed only when there is positive numbers.

• Tony Sun says:

You should double check whether you know what you are talking about next time before you criticise someone else’s solution!

• Tony Sun says:

This is less optimal though still O(n) it has to find out the max of A first; max itself is O(n).

2. Greg says:

How this problem differs from max slice problem described in the lesson (https://codility.com/media/train/7-MaxSlice.pdf)?
O(n) algorithm presented at the end is very similar to your solution and it works fine as long as slice sums are positive. Lesson does not mention negative numbers handling though

• Sheng says:

In the lesson, the slice could be empty, whose sum is zero. Therefore the maximum slice sum would zeor or more.

In the execise, the slice could NOT be empty. And the maximum slice sum might be negative.

• Tony Sun says:

I don’t think the key difference is whether the array can be empty. I think algorithm in the lessson is fundamentally wrong. Because it initialises both max_ending and max_slice to be 0, hence the algorithm in the lesson won’t work for a single negative array e.g. A = [-10]. What’s funy is in the lesson it did mention the array elements can be negative.

I am really surprised that as of today (Nov 2016) Codility hasn’t really fixed this, probably because nobody bothers reporting it.

• Sheng says:

I believe the lesson is correct. When A = [-10], the result is 0, as the maximum slice is an empty slice [].

As I said, in the lesson, empty slice is permitted, while it’s not in the practice.

3. rishi says:

This solution fails for solution [-2,1]

• Sheng says:

Returned value: 1
Why is it incorrect?

4. What would be the result for this input ? [3, 3, -2, 2, 4, 0]

• Sheng says:

10