Leetcode 3523. Make Array Non-decreasing

  • [Leetcode 3523. Make Array Non-decreasing](#Leetcode 3523. Make Array Non-decreasing)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题思路上来说就是一个栈的问题,就是从后往前依次考察每一个元素,显然,当前位置要么被舍弃,要么被保留,但是无论如何其对应位置一定会留下一个至少不小于当前元素大小的新元素,因此,后续所有比起更小的元素都无法被保留。

由此,这就变成了一个标准的栈的问题,但是需要注意的是,如果完全使用栈,还是会出现超时的问题,因此我们对相同元素进行了合并,这样的话可以优化效率,使之可以通过全部测试。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def maximumPossibleSize(self, nums: List[int]) -> int:
        # n = len(nums)
        ans = []
        for x in nums[::-1]:
            while ans != [] and ans[0][0] < x:
                ans.pop(0)
            if ans == [] or ans[0][0] > x:
                ans.insert(0, (x, 1))
            else:
                ans[0] = (ans[0][0], ans[0][1] + 1)
        return sum([x[1] for x in ans])

提交代码评测得到:耗时356ms,占用内存37.8MB。

相关推荐
Navigator_Z15 小时前
LeetCode //C - 1240. Tiling a Rectangle with the Fewest Squares
c语言·算法·leetcode
稻米哟15 小时前
力扣100——双指针
算法·leetcode
橘子汽水16818 小时前
Leetcode 198,118打家劫舍,杨辉三角
算法·leetcode
alphaTao1 天前
LeetCode 每日一题 2026/9/7-2026/9/13
算法·leetcode
土司大王1 天前
LeetCode 79 单词搜索:Java 回溯模板、网格 DFS 与剪枝优化
java·算法·leetcode·深度优先
All for pursuit.1 天前
【数组-5】560.和为K的子数组
数据结构·c++·算法·leetcode
土司大王2 天前
LeetCode 17 电话号码的字母组合:Java 回溯模板、多叉决策树与复杂度分析
java·leetcode·决策树
find1star2 天前
LeetCode 25:K 个一组翻转链表
java·数据结构·算法·leetcode·链表·职场和发展·动态规划