求最大字串 - 值小於等於給定值

We define a subarray of array a to be a contiguous block of a's elements having a length that is less than or equal to the length of array a. For example, the subarrays of array a = [1, 2, 3] are [1][2][1, 2][2, 3], and [1, 2, 3]. Now, let's say we have an integer, k = 3. The subarrays of a having elements that sum to a number ≤ k are [1][2], and [1, 2]. The longest of these subarrays is [1, 2], which has a length of 2.

 

Complete the maxLength function in the editor. It has 2 parameters:

  1. An array of integers, a.
  2. An integer, k.

The function must return the length of the longest subarray having elements that sum to a number less than or equal to k.



  • 簡單解法
static int maxLength(int[] a, int k) {
        int result = -1;
        for (int start = 0; start < a.length; start++) {
            int sum = 0;
            int cnt = 0;
            int i = start;
            while (i < a.length && sum + a[i] <= k) {
                sum += a[i++];
                cnt++;
            }
            result = Math.max(cnt, result);            
        }
        return result;
}



  • 優化解法

此種解法有很多的優化空間,例如在進行以第二個元素開頭的嘗試時,除了第一個元素外,第一次嘗試的序列一定都在第二次嘗試的序列內,
所以可以減去第一個元素,然後在此基礎上在尾部加入新的元素;

 static int maxLength(int[] a, int k) {
        int result = -1;
        int start = 0;
        int sum = 0, cnt = 0;
        int i = start;
        while (i < a.length && sum + a[i] <= k) {
            sum += a[i++];
            cnt++;
        }
        result = cnt;
        
        while (start < a.length) {
            sum -= a[start++];
            cnt--;
            while (i < a.length && sum + a[i] <= k) {
                sum += a[i++];
                cnt++;
            }            
            result = Math.max(cnt, result); 
            if (i >= a.length) break;
        }    
        return result;
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章