3113. 边界元素是最大值的子数组数目

Powered by:NEFU AB-IN

Link

文章目录

  • [3113. 边界元素是最大值的子数组数目](#3113. 边界元素是最大值的子数组数目)

3113. 边界元素是最大值的子数组数目

题意

给你一个 正 整数数组 nums 。

请你求出 nums 中有多少个子数组,满足子数组中 第一个 和 最后一个 元素都是这个子数组中的 最大 值。

思路

  1. st表
    找每个数x出现的下标,并判断当x和前一个x之间的最大值等于x时,记录下标;如果不是x,说明区间断了,那么就统计之前记录的下标,结果为 n * (n + 1) // 2,n为下标数组长度,并清空数组,加入新下标。最后将所有的非空下标数组都做一遍统计
  2. 单调栈
    https://leetcode.cn/problems/find-the-number-of-subarrays-where-boundary-elements-are-maximum/solutions/2738894/on-dan-diao-zhan-pythonjavacgo-by-endles-y00d/
    利用单调栈(处理两边比自己大或小的第一个元素)去清理掉垃圾数据,维护一个底大顶小的单调栈,记录元素及其出现次数。对栈顶元素判断大小

代码

python 复制代码
'''
Author: NEFU AB-IN
Date: 2024-08-01 19:55:47
FilePath: \LeetCode\3113\3113.py
LastEditTime: 2024-08-01 20:49:33
'''
# 3.8.19 import
import random
from collections import Counter, defaultdict, deque
from datetime import datetime, timedelta
from functools import lru_cache, reduce
from heapq import heapify, heappop, heappush, nlargest, nsmallest
from itertools import combinations, compress, permutations, starmap, tee
from math import ceil, comb, fabs, floor, gcd, hypot, log, perm, sqrt
from string import ascii_lowercase, ascii_uppercase
from sys import exit, setrecursionlimit, stdin
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union

# Constants
TYPE = TypeVar('TYPE')
N = int(2e5 + 10)
M = int(20)
INF = int(1e12)
OFFSET = int(100)
MOD = int(1e9 + 7)

# Set recursion limit
setrecursionlimit(int(2e9))


class Arr:
    array = staticmethod(lambda x=0, size=N: [x() if callable(x) else x for _ in range(size)])
    array2d = staticmethod(lambda x=0, rows=N, cols=M: [Arr.array(x, cols) for _ in range(rows)])
    graph = staticmethod(lambda size=N: [[] for _ in range(size)])


class Math:
    max = staticmethod(lambda a, b: a if a > b else b)
    min = staticmethod(lambda a, b: a if a < b else b)


class IO:
    input = staticmethod(lambda: stdin.readline().rstrip("\r\n"))
    read = staticmethod(lambda: map(int, IO.input().split()))
    read_list = staticmethod(lambda: list(IO.read()))


class Std:
    class SparseTable:
        def __init__(self, data: list, func=lambda x, y: x | y):
            """Initialize the Sparse Table with the given data and function."""
            self.func = func
            self.st = [list(data)]
            i, n = 1, len(self.st[0])
            while 2 * i <= n:
                pre = self.st[-1]
                self.st.append([func(pre[j], pre[j + i]) for j in range(n - 2 * i + 1)])
                i <<= 1

        def query(self, begin: int, end: int):
            """Query the combined result over the interval [begin, end]."""
            lg = (end - begin + 1).bit_length() - 1
            return self.func(self.st[lg][begin], self.st[lg][end - (1 << lg) + 1])

# --------------------------------------------------------------- Division line ------------------------------------------------------------------


class Solution:
    def numberOfSubarrays(self, nums: List[int]) -> int:
        st = Std.SparseTable(nums, Math.max)
        index_list_dict = defaultdict(list)
        res = 0
        for i, num in enumerate(nums):
            list_ = index_list_dict[num]
            if list_:
                pre_id = list_[-1]
                if st.query(pre_id, i) == num:
                    list_.append(i)
                else:
                    res += len(list_) * (len(list_) + 1) // 2
                    list_.clear()
                    list_.append(i)
            else:
                list_.append(i)

        for _, list_ in index_list_dict.items():
            res += len(list_) * (len(list_) + 1) // 2
        return res
python 复制代码
class Solution:
    def numberOfSubarrays(self, nums: List[int]) -> int:
        ans = len(nums)
        st = [[inf, 0]]  # 无穷大哨兵
        for x in nums:
            while x > st[-1][0]:
                st.pop()
            if x == st[-1][0]:
                ans += st[-1][1]
                st[-1][1] += 1
            else:
                st.append([x, 1])
        return ans
相关推荐
Bigcrab__5 分钟前
Python3网络爬虫开发实战(15)Scrapy 框架的使用(第一版)
爬虫·python·scrapy
易辰君1 小时前
Python编程 - 协程
开发语言·python
宇宙第一小趴菜1 小时前
探索网络世界:TCP/IP协议、Python Socket编程及日常生活比喻
网络·python·tcp/ip
小黑031 小时前
Phoenix使用
开发语言·python
南斯拉夫的铁托1 小时前
(PySpark)RDD实验实战——求商品销量排行
python·spark·pyspark
kay_5451 小时前
YOLOv8改进 | 模块缝合 | C2f 融合SCConv提升检测性能【CVPR2023】
人工智能·python·深度学习·yolo·目标检测·面试·yolov8改进
kngines1 小时前
【PLW004】基于Python网络爬虫与推荐算法的新闻推荐平台v1.0(Python+Django+NLP+Vue+MySQL前后端分离)
爬虫·python·nlp·推荐算法
激动的兔子2 小时前
Python_两个jpg图片文件名称互换
python
计算机学姐2 小时前
基于python+django+vue的医院预约挂号系统
开发语言·vue.js·后端·python·mysql·django·tornado
嵌入式杂谈2 小时前
计算机视觉——基于OpenCV和Python进行模板匹配
python·opencv·计算机视觉