Saturday, September 23, 2017

Codility - Lesson 9 Maximum Slice Problem - 3. MaxSliceSum

Source Link:
https://codility.com/programmers/lessons/9-maximum_slice_problem/max_slice_sum/

Question:
A non-empty zero-indexed array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P ≤ Q < 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).
Assume that:
  • 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].
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified. 

My Solution:
Notes:
1. elegant solution
// not using "Math.max( 0, maxEndingHere + A[i])"
// Instead, using "Math.max( A[i], maxEndingPrevious + A[i] )" 
2. initial setting A[0]
int maxEndingPrevious = A[0];
int maxEndingHere = A[0];
int maxSoFar = A[0];
// note: for i=0, it will return A[0] (also for "one element" cases) 
3. 
for(int i = 1; i < A.length; i++){
maxEndingHere = Math.max(A[i], maxEndingPrevious + A[i]); // <--- key point~!!
maxEndingPrevious = maxEndingHere;
maxSoFar = Math.max(maxSoFar, maxEndingHere); // update the max (be careful)
}
return maxSoFar; // can be used for "all negative" cases   

1 comment:

  1. Probably the most simple soln , makes much more sense than calculation avg and comparing indexs , this is what was coming to mind but putting it into lines is the art , well done!

    ReplyDelete

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...