求最大字串 - 值小于等于给定值

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;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值