Advertisement
sweet1cris

Untitled

Jan 9th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. public class Solution {
  2.     /**
  3.      * @param nums an array of integers
  4.      * @param k1 an integer
  5.      * @param k2 an integer
  6.      * @return the largest sum
  7.      */
  8.     public int maxSubarray5(int[] nums, int k1, int k2) {
  9.         // Write your code here
  10.         int n = nums.length;
  11.         if (n < k1)
  12.             return 0;
  13.  
  14.         int result = Integer.MIN_VALUE;
  15.  
  16.         int[] sum = new int[n + 1];
  17.         sum[0] = 0;
  18.         LinkedList<Integer> queue = new LinkedList<Integer>();
  19.  
  20.         for (int i = 1; i <= n; ++i) {
  21.             sum[i] = sum[i - 1] + nums[i - 1];
  22.  
  23.             if (!queue.isEmpty() && queue.getFirst() < i - k2) {
  24.                 queue.removeFirst();
  25.             }
  26.             if (i >= k1) {
  27.                 while (!queue.isEmpty() && sum[queue.getLast()] > sum[i - k1]) {
  28.                     queue.removeLast();
  29.                 }
  30.                 queue.add(i - k1);
  31.             }
  32.  
  33.             // [i - k2, i - k1]
  34.             if (!queue.isEmpty() && sum[i] - sum[queue.getFirst()] > result) {
  35.                 result = Math.max(result, sum[i] - sum[queue.getFirst()]);
  36.             }
  37.  
  38.  
  39.         }
  40.         return result;
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement