Skip to content

Instantly share code, notes, and snippets.

@codegagan
Created May 20, 2019 05:33
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 codegagan/b8e6de4586d067772082c2b73fc79fa0 to your computer and use it in GitHub Desktop.
Save codegagan/b8e6de4586d067772082c2b73fc79fa0 to your computer and use it in GitHub Desktop.
Codility test problem find sum of two sub arrays of fixed length
// you can also use imports, for example:
// import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A, int K, int L) {
// write your code in Java SE 8
if(K + L > A.length){
return -1;
}
// Fix max of K sliding window
int max =-1;
for(int i =0; i+K <= A.length; i+=L){
int kSum =0;
for(int j=i; j<K+i;j++){
kSum+=A[j];
}
// System.out.println("ksum: "+kSum);
int maxL = 0;
for(int k =0; k+L<i;k++){
int lSum =0;
for(int l =k; l<k+L ;l++){
lSum+=A[l];
}
maxL = Math.max(maxL,lSum);
}
// System.out.println("first maxL: "+ maxL);
for(int m =i+K; m+L<= A.length;m++){
int lSum =0;
for(int n =m; n<m+L ;n++){
lSum+=A[n];
}
// System.out.println("lsum "+lSum);
maxL = Math.max(maxL,lSum);
}
// System.out.println("second maxL: "+ maxL);
max = Math.max(max,kSum + maxL);
// System.out.println("maxL: "+ maxL);
// System.out.println("-------------------");
}
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment