Skip to content

Instantly share code, notes, and snippets.

@hrubantjakub1
Created April 21, 2017 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrubantjakub1/8fcea8a1c3649f01eb00ea137d068e95 to your computer and use it in GitHub Desktop.
Save hrubantjakub1/8fcea8a1c3649f01eb00ea137d068e95 to your computer and use it in GitHub Desktop.
maxdoubleslicesum one of codility tasks Java + codesays community solution in Python
// my solution is based on iterating all the list comparing all possible sums and find the max sum.
class Solution {
public static int solution(int[] A) {
int length = A.length;
int max = 0;
int sum = 0;
for (int x = 0; x < length - 4; x++) {
for (int y = x + 2; y < length - 2; y++) {
for (int z = y + 2; z < length; z++) {
for (int l = x + 1; l <= (y - 1); l++) {
sum += A[l];
}
for (int m = y + 1; m <= (z - 1); m++) {
sum += A[m];
}
if (sum > max) {
max = sum;
}
sum = 0;
}
}
}
return max;
}
// for comparison there is https://codesays.com/2014/solution-to-max-double-slice-sum-by-codility/
// solution, using very clever but very rare algorithm, written in python
def solution(A):
A_len = len(A) # The length of array A
# Get the sum of maximum subarray, which ends this position
# Method: http://en.wikipedia.org/wiki/Maximum_subarray_problem
max_ending_here = [0] * A_len
max_ending_here_temp = 0
for index in xrange(1, A_len-2):
max_ending_here_temp = max(0, A[index]+max_ending_here_temp)
max_ending_here[index] = max_ending_here_temp
# Get the sum of maximum subarray, which begins this position
# The same method. But we travel from the tail to the head
max_beginning_here = [0] * A_len
max_beginning_here_temp = 0
for index in xrange(A_len-2, 1, -1):
max_beginning_here_temp = max(0, A[index]+max_beginning_here_temp)
max_beginning_here[index] = max_beginning_here_temp
# Connect two subarray for a double_slice. If the first subarray
# ends at position i, the second subarray starts at position i+2.
# Then we compare each double slice to get the one with the
# greatest sum.
max_double_slice = 0
for index in xrange(0, A_len-2):
max_double_slice = max(max_double_slice,
max_ending_here[index] + max_beginning_here[index+2] )
return max_double_slice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment