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_Z13 小时前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
青山木15 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
All for pursuit.18 小时前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
All for pursuit.1 天前
【回溯-5】78.子集
数据结构·c++·算法·leetcode
代码什么用1 天前
LeetCode-560.和为 K 的子数组
算法·leetcode
All for pursuit.1 天前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode
yi0111 天前
DAY19: LeetCode 28 找出字符串中第一个匹配项的下标
人工智能·笔记·python·算法·leetcode
不会就选b1 天前
算法日常・每日刷题--<动态规划>6
数据结构·算法·leetcode
0+1112 天前
算法 --模拟
c++·算法·leetcode
Nil2082 天前
leetcode 739每日温度
算法·leetcode·职场和发展