Advertisement
sweet1cris

Untitled

Jan 9th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. public class Solution {
  2.     /**
  3.      * @param nums: A list of integers
  4.      * @return: An integer denotes the sum of max two non-overlapping subarrays
  5.      */
  6.     public int maxTwoSubArrays(ArrayList<Integer> nums) {
  7.         // write your code
  8.         int size = nums.size();
  9.         int[] left = new int[size];
  10.         int[] right = new int[size];
  11.         int sum = 0;
  12.         int minSum = 0;
  13.         int max = Integer.MIN_VALUE;
  14.         for(int i = 0; i < size; i++){
  15.             sum += nums.get(i);
  16.             max = Math.max(max, sum - minSum);
  17.             minSum = Math.min(sum, minSum);
  18.             left[i] = max;
  19.         }
  20.         sum = 0;
  21.         minSum = 0;
  22.         max = Integer.MIN_VALUE;
  23.         for(int i = size - 1; i >= 0; i--){
  24.             sum += nums.get(i);
  25.             max = Math.max(max, sum - minSum);
  26.             minSum = Math.min(sum, minSum);
  27.             right[i] = max;
  28.         }
  29.         max = Integer.MIN_VALUE;
  30.         for(int i = 0; i < size - 1; i++){
  31.             max = Math.max(max, left[i] + right[i + 1]);
  32.         }
  33.         return max;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement