number-of-subarrays-with-bounded-maximum 最大值在界内的子数组个数

给定一个包含正整数的数组A , 以及两个正整数 LR (L <= R).

返回最大元素值在范围[L, R]之间的子数组(连续, 非空)的个数,

number-of-subarrays-with-bounded-maximum

样例

样例 1:

输入: A = [2, 1, 4, 3], L = 2, R = 3
输出: 3
解释: 有三个子数组满足要求:[2], [2, 1], [3].

样例 2:

输入: A = [7,3,6,7,1], L = 1, R = 4
输出: 2
思路1  O(N^2)、遍历数组 设置一个 max 值,在遍历数组 取出最大值,如果当前 a[j] > r 跳出循环,如果 a[j] >== l result++, 整体思想有点 dp 的感觉


思路2  O(N)、遍历数组,记录下符合位置的索引 index ,和不符合位置的索引 temp ,result += index - temp 



public class Solution {
    /**
     * @param a: an array
     * @param l: an integer
     * @param r: an integer
     * @return: the number of subarrays such that the value of the maximum array element in that subarray is at least l and at most R
     */
    public int numSubarrayBoundedMax(int[] a, int l, int r) {
        // Write your code here
        int result = 0;
        for (int i = 0; i < a.length; i++) {
            int max = Integer.MIN_VALUE;
            for (int j = i; j < a.length; j++) {
                max = Math.max(max, a[j]);
                if (max > r) {
                    break;
                }
                if (max >= l) {
                    result++;
                }
            }
        }
        return result;
    }
}
public class Solution {
   
    /**
     * @param a: an array
     * @param l: an integer
     * @param r: an integer
     * @return: the number of subarrays such that the value of the maximum array element in that subarray is at least l and at most R
     */
    public int numSubarrayBoundedMax(int[] a, int l, int r) {
        // Write your code here
        int result = 0;
        int index = -1;
        int temp = -1;
        for (int i = 0; i < a.length; i++) {
            if (a[i] > r) {
                index = temp = i;
                continue;
            }
            if (a[i] >= l) {
                index = i;
            }
            result += index - temp;
        }
        return result;
    }

}


GitHub: https://github.com/xingfu0809/Java-LintCode

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容