LeetCode //C - 962. Maximum Width Ramp

962. Maximum Width Ramp

A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i.

Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.

Example 1:

Input: nums = [6,0,8,2,1,5]
Output: 4
Explanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.

Example 2:

Input: nums = [9,8,1,0,1,9,4,0,4,1]
Output: 7
Explanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.

Constraints:
  • 2 < = n u m s . l e n g t h < = 5 ∗ 10 4 2 <= nums.length <= 5 * 10^4 2<=nums.length<=5∗104
  • 0 < = n u m s [ i ] < = 5 ∗ 10 4 0 <= nums[i] <= 5 * 10^4 0<=nums[i]<=5∗104

From: LeetCode

Link: 962. Maximum Width Ramp


Solution:

Ideas:
  • Build a monotonic decreasing stack of indices from left to right.

    → Stack keeps positions where nums[i] is a new minimum.

  • A smaller left value has the best chance to form the widest ramp later.

  • Traverse from the right to left (j from end to start):

    → If nums[stack[top]] <= nums[j], then (stack[top], j) forms a valid ramp.

  • Calculate width j - stack[top], update maximum width.

  • Pop the index from the stack because earlier j will produce smaller widths.

  • Continue until stack is empty or j is done.

  • Return the maximum width found.

Code:
c 复制代码
int maxWidthRamp(int* nums, int numsSize) {
    if (numsSize < 2) return 0;

    // Monotonic decreasing stack of indices
    int *stack = (int *)malloc(numsSize * sizeof(int));
    int top = -1;

    // Build stack: store indices where nums[i] is a new minimum from the left
    for (int i = 0; i < numsSize; ++i) {
        if (top == -1 || nums[i] < nums[stack[top]]) {
            stack[++top] = i;
        }
    }

    int maxWidth = 0;

    // Scan from the right, try to widen ramps using the stack
    for (int j = numsSize - 1; j >= 0 && top >= 0; --j) {
        // While current value can form a ramp with stack[top]
        while (top >= 0 && nums[stack[top]] <= nums[j]) {
            int width = j - stack[top];
            if (width > maxWidth) maxWidth = width;
            --top;  // Pop because any earlier j will only give smaller width
        }
    }

    free(stack);
    return maxWidth;
}
相关推荐
淘矿人20 分钟前
Claude辅助DevOps实践
java·大数据·运维·人工智能·算法·bug·devops
Cosolar27 分钟前
万字详解:RAG 向量索引算法与向量数据库架构及实战
数据库·人工智能·算法·数据库架构·milvus
三品吉他手会点灯1 小时前
C语言学习笔记 - 40.数据类型 - scanf函数的编程规范与非法输入处理
c语言·开发语言·笔记·学习
落羽的落羽2 小时前
【算法札记】练习 | Week4
linux·服务器·数据结构·c++·人工智能·算法·动态规划
萑澈3 小时前
算法竞赛入门:C++ STL核心用法与时空复杂度速查手册
数据结构·c++·算法·stl
Godspeed Zhao3 小时前
从零开始学AI16——SVM
算法·机器学习·支持向量机
江屿风3 小时前
C++OJ题经验总结(竞赛)1
开发语言·c++·笔记·算法
nebula-AI3 小时前
人工智能导论:模型与算法(核心技术)
人工智能·深度学习·神经网络·算法·机器学习·集成学习·sklearn
运筹vivo@4 小时前
LeetCode 2405. 子字符串的最优划分
c++·算法·leetcode·职场和发展·哈希表