Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void main(String[] args) {
- int[] arr = {6, 1, 4, 6, 3, 2, 7, 4};
- int ret = solution1(arr, 3, 2);
- System.out.println(ret);
- }
- public static int solution1(int[] A, int K, int L) {
- int ret = -1;
- if ((K+L) > A.length) {
- return -1;
- }
- else if ((K+L) == A.length) {
- //Count all of the items in A
- int sum = 0;
- for (int i : A){
- sum += i;
- }
- return sum;
- }
- int kPlusL = 0;
- int[] maxAndStartIndex = getMaxContiguosFromArray(A, K);
- kPlusL+=maxAndStartIndex[0];
- //System.out.println(maxAndStartingIndex[0]);
- int[] leadingElements = Arrays.copyOfRange(A, 0, maxAndStartIndex[1]);
- int[] trailingElements = Arrays.copyOfRange(A, (maxAndStartIndex[1]+K), A.length);
- int[] array1and2 = new int[leadingElements.length + trailingElements.length];
- System.arraycopy(leadingElements, 0, array1and2, 0, leadingElements.length);
- System.arraycopy(trailingElements, 0, array1and2, leadingElements.length, trailingElements.length);
- int[] maxAndStartingIndex = getMaxContiguosFromArray(array1and2, L);
- //System.out.println(maxAndStartingIndex[0]);
- kPlusL+=maxAndStartingIndex[0];
- //System.out.println(kPlusL);
- return kPlusL;
- }
- static int[] getMaxContiguosFromArray(int[] a, int numEl){
- int firstSum = 0;
- int firstPrevSum = 0;
- int startIndex = 0;
- int[] maxAndStartIndex = new int[2];
- for(int i = 0; i < a.length; i++){
- if(i <= a.length - numEl) {
- for (int j = i; j < i + numEl; j++) {
- firstSum += a[j];
- }
- }
- if(firstSum > firstPrevSum) {
- firstPrevSum = firstSum;
- startIndex = i;
- }
- firstSum = 0;
- }
- maxAndStartIndex[0] = firstPrevSum;
- maxAndStartIndex[1] = startIndex;
- return maxAndStartIndex;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement