Find the largest sum of any slice inside an array This is the 26th exercise I solved from Codility. It scores 100%. I think I improved a lot since I started with this lessons, around 2 months ago, but still every post I made had things to be improved. What do you think about this code?


  Task description





  A non-empty array A consisting of N integers is
  given. A pair of integers (P, Q), such that 0 ≤ P ≤ Q &lt; N, is called a
  slice of array A. The sum of a slice (P, Q) is the total of A[P] +
  A[P+1] + ... + A[Q].
  
  Write a function:
  
  class Solution { public int solution(int[] A); }
  
  that, given an array A consisting of N integers, returns the maximum
  sum of any slice of A.
  
  For example, given array A such that:
  
  A[0] = 3  A[1] = 2  A[2] = -6 A[3] = 4  A[4] = 0 the function should
  return 5 because:
  
  (3, 4) is a slice of A that has sum 4, (2, 2) is a slice of A that has
  sum −6, (0, 1) is a slice of A that has sum 5, no other slice of A has
  sum greater than (0, 1). Write an efficient algorithm for the
  following assumptions:
  
  N is an integer within the range [1..1,000,000]; each element of array
  A is an integer within the range [−1,000,000..1,000,000]; the result
  will be an integer within the range [−2,147,483,648..2,147,483,647].


[PS: I'll upvote suggestions about sites that can help me get better at databases that follow a similar approach to codility]

using System;

class Solution {
    public int solution(int[] A) {
        var lastAddend = 0;
        var accumulator = 0 ; 
        var maxSliceSum = A.Length &gt; 0 ? A[0] : 0 ;
        foreach(var addend in A)
        {
            var maxLastPair = Math.Max(addend, lastAddend + addend);
            accumulator = maxLastPair &gt; accumulator + addend ? maxLastPair : accumulator + addend;
            maxSliceSum = Math.Max(maxSliceSum, accumulator);
            lastAddend = addend;
        }
        return maxSliceSum;
    }
}
Two minor remarks:


For consistency sake, this

accumulator = maxLastPair &gt; accumulator + addend ? maxLastPair : accumulator + addend;


can be implemented similar to the other statements as 

accumulator = Math.Max(maxLastPair, accumulator + addend);

Some comments would be welcome in the loop. What exactly is the idea behind the different variables you keep. It took me a while to convince myself that your method was working as it should.