前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LWC 74: 795. Number of Subarrays with Bounded Maximum

LWC 74: 795. Number of Subarrays with Bounded Maximum

作者头像
用户1147447
发布2019-05-26 00:21:07
2600
发布2019-05-26 00:21:07
举报
文章被收录于专栏:机器学习入门

LWC 74: 795. Number of Subarrays with Bounded Maximum

Problem:

We are given an array A of positive integers, and two positive integers L and R (L <= R). Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element in that subarray is at least L and at most R.

Example :

Input: A = [2, 1, 4, 3] L = 2 R = 3 Output: 3 Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].

Note:

  • L, R and A[i] will be an integer in the range [0, 10^9].
  • The length of A will be in the range of [1, 50000].

思路: 先关注一波性质,在L和R之间的最大值val符合 val in [L, R], 可以转为:求区间内的任意值x , x in [L, R]。所以,把数组的每个位置当作起点,如A = [2, 1, 4, 3]:

代码语言:javascript
复制
位置0: [2], [2, 1], [2, 1, 4], [2, 1, 4, 3]
位置1: [1], [1, 4], [1, 4, 3]
位置2: [4], [4, 3]
位置3: [3]

for each subset in each position:
calculate whether the last value in subset <= R

你会发现,考虑位置0,subset[2, 1, 4]中的last value 4时,因为4 > R,所以删除该subset,且连同位置1,2,3中包含4的子集可以一并删除。

代码如下:

代码语言:javascript
复制
    public int numSubarrayBoundedMax(int[] A, int L, int R) {
        return count(A, R) -count(A, L - 1);
    }

    int count(int[] a, int r) {
        int ret = 0;
        int cnt = 0;
        for (int v : a) {
            if (v <= r) cnt ++;
            else cnt = 0;
            ret += cnt;
        }
        return ret;
    }

Python版本:

代码语言:javascript
复制
class Solution(object):
    def numSubarrayBoundedMax(self, A, L, R):
        """
        :type A: List[int]
        :type L: int
        :type R: int
        :rtype: int
        """
        def count(A, R):
            ret = cnt = 0
            for v in A:
                cnt = cnt + 1 if v <= R else 0
                ret += cnt
            return ret

        return count(A, R) - count(A, L - 1)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年03月06日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LWC 74: 795. Number of Subarrays with Bounded Maximum
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档