FB面經prepare: 3 Window Max Sum

Given a num array, find a window of size k, that has a maximum sum of the k entries.
follow-up: Find three non-overlap windows of size k, that together has a maximum sum of the 3k entries, time complexity O(n^2)

Follow Up:windows

這個其實能夠優化到O(n)時間。
建從左端到每一個下標的最大window數組,再建從右端到每一個下標的最大window數組。
再從左往右走一遍全部的size k window,將其和與上一步建的兩個數組一塊兒加起來。遍歷一遍取最大值便可。數組

 1 package fbOnsite;
 2 
 3 public class ThreeWindow {
 4     public static int find(int[] arr, int k) {
 5         int res = Integer.MIN_VALUE;
 6         int len = arr.length;
 7         int[] left = new int[len];
 8         
 9         int lsum = 0;
10         for (int i=0; i<len; i++) {
11             lsum += arr[i];
12             if (i >= k) lsum -= arr[i-k];
13             if (i >= k-1) left[i] = Math.max(lsum, i>=1? left[i-1] : 0);//find the window end at i with max sum
14         }
15         
16         int[] right = new int[len];
17         int rsum = 0;
18         for (int j=len-1; j>=0; j--) {
19             rsum += arr[j];
20             if (j < len-k) rsum -= arr[j+k];
21             if (j <= len-k) right[j] = Math.max(rsum, j<len-1? right[j+1] : 0);
22         }
23         
24         int midSum = 0;
25         for (int t=k; t<=len-k-1; t++) {
26             midSum += arr[t];
27             if (t >= k + k) midSum -= arr[t-k];
28             if (t >= k + k - 1) { // for each size k window in the middle with sum as midSum
29                 //find midSum + left[t-k] + right[t+1] that gives the max
30                 res = Math.max(res, midSum + left[t-k] + right[t+1]);
31             } 
32         }
33         return res;
34     }
35 
36     /**
37      * @param args
38      */
39     public static void main(String[] args) {
40         // TODO Auto-generated method stub
41         int[] arr = new int[]{2,1,1,-1,3,6,-2,-4,1,2,-1,2,1,-1,2};
42         int[] arr1 = new int[]{1,2,2,-1,1,2,1,3,5};
43         int res = find(arr, 3);
44         System.out.println(res);
45     }
46 
47 }
相關文章
相關標籤/搜索