Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. public static void main(String[] args) {
  2. int[] arr = {6, 1, 4, 6, 3, 2, 7, 4};
  3. int ret = solution1(arr, 3, 2);
  4. System.out.println(ret);
  5. }
  6.  
  7. public static int solution1(int[] A, int K, int L) {
  8. int ret = -1;
  9.  
  10. if ((K+L) > A.length) {
  11. return -1;
  12. }
  13. else if ((K+L) == A.length) {
  14. //Count all of the items in A
  15. int sum = 0;
  16.  
  17. for (int i : A){
  18. sum += i;
  19. }
  20.  
  21. return sum;
  22. }
  23.  
  24. int kPlusL = 0;
  25.  
  26. int[] maxAndStartIndex = getMaxContiguosFromArray(A, K);
  27. kPlusL+=maxAndStartIndex[0];
  28. //System.out.println(maxAndStartingIndex[0]);
  29. int[] leadingElements = Arrays.copyOfRange(A, 0, maxAndStartIndex[1]);
  30. int[] trailingElements = Arrays.copyOfRange(A, (maxAndStartIndex[1]+K), A.length);
  31.  
  32. int[] array1and2 = new int[leadingElements.length + trailingElements.length];
  33. System.arraycopy(leadingElements, 0, array1and2, 0, leadingElements.length);
  34. System.arraycopy(trailingElements, 0, array1and2, leadingElements.length, trailingElements.length);
  35.  
  36. int[] maxAndStartingIndex = getMaxContiguosFromArray(array1and2, L);
  37. //System.out.println(maxAndStartingIndex[0]);
  38. kPlusL+=maxAndStartingIndex[0];
  39. //System.out.println(kPlusL);
  40.  
  41. return kPlusL;
  42. }
  43.  
  44. static int[] getMaxContiguosFromArray(int[] a, int numEl){
  45. int firstSum = 0;
  46. int firstPrevSum = 0;
  47. int startIndex = 0;
  48. int[] maxAndStartIndex = new int[2];
  49. for(int i = 0; i < a.length; i++){
  50. if(i <= a.length - numEl) {
  51. for (int j = i; j < i + numEl; j++) {
  52. firstSum += a[j];
  53. }
  54. }
  55.  
  56. if(firstSum > firstPrevSum) {
  57. firstPrevSum = firstSum;
  58. startIndex = i;
  59.  
  60. }
  61. firstSum = 0;
  62. }
  63. maxAndStartIndex[0] = firstPrevSum;
  64. maxAndStartIndex[1] = startIndex;
  65. return maxAndStartIndex;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement