将所有元素变为0的最少操作次数

LeetCode3542-将所有元素变为0的最少操作次数

#resource / algorithm #type / snippet #status / evergreen #source / leetcode #algo / monotonic-stack #ds / stack

[!info] related notes 算法面试题型 MOC 单调栈

将所有元素变为 0 的最少操作次数

题目

3542. 将所有元素变为 0 的最少操作次数 - 力扣(LeetCode)

题解

单调栈

var minOperations = function (nums) {
	// 给最后一位后面添加 0,确保最后一位的变化能记录
    nums.push(0);
    let st = [0];
    let res = 0;
    for (const a of nums) {
        while (st.length && a < st[st.length - 1]) {
            st.pop();
            res++;
        }
        if (a === st[st.length - 1]) {
            continue;
        }
        st.push(a);
        // console.log(a,st)
    }
    return res;
};

参考

3542. 将所有元素变为 0 的最少操作次数 - 力扣(LeetCode)

创建于 2025/1/1 更新于 2026/5/27