Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static int maxSubArray(int[] array){
- // We make a new array to store the sum of the maximal subarray up till that index in the original array
- int[] B = new int[array.length];
- // A subarray of length 0 has a value of 0
- B[0] = Math.max(array[0], 0);
- /* The maximal starts at 0, because you can always have a subarray that has a length of 0
- * making the value 0 (even if the subarrays with length equal or bigger than 1 have negative values).
- */
- int max = B[0];
- // We loop through every element in the original array
- for(int i = 1; i < array.length; i++){
- /* The sum of the maximal subarray at index i is maximal value of:
- * the sum of an empty subarray (0) or the sum of maximal subarray at index i - 1 and the value at index i.
- * Because you store the maximal sum of subarrays for every index, you can use these to calculate the sum of subarrays containing
- * elements at higher indices.
- */
- B[i] = Math.max(0, B[i - 1] + array[i]);
- /* the new maximal value is either the maximal value over all, or (if the value at B[i]) is bigger than the max up till then) B[i]
- *
- */
- max = Math.max(max, B[i]);
- }
- // In the end you return the max value
- return max;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement