leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit 7187348d45fa427319707488e5affe5d5b97f708
parent 0bc0cb90d1af8a72f45dfe7fe93025c368a2790d
Author: Jack Sangdahl <jack@pngu.org>
Date:   Wed,  9 Oct 2024 22:02:23 -0600

962. maximum width ramp

Diffstat:
Amaximum_width_ramp.c | 33+++++++++++++++++++++++++++++++++
Amaximum_width_ramp.py | 30++++++++++++++++++++++++++++++
2 files changed, 63 insertions(+), 0 deletions(-)

diff --git a/maximum_width_ramp.c b/maximum_width_ramp.c @@ -0,0 +1,33 @@ +// 962. Maximum Width Ramp +#include "leetcode.h" + +/* + * 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 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 + */ + +int maxWidthRamp(int *nums, int numsSize) { + int ans = 0, idx = 0; + int *stack = (int *)malloc(numsSize * sizeof(int)); + for (int i = 0; i < numsSize; i++) { + if (!idx) + stack[idx++] = i; + else { + if (nums[i] <= nums[stack[idx - 1]]) + stack[idx++] = i; + } + } + for (int i = numsSize - 1; i >= 0; i--) + while (idx && nums[i] >= nums[stack[idx - 1]]) + ans = fmax(ans, i - stack[--idx]); + free(stack); + return ans; +} + +int main() { + int n1[] = {6, 0, 8, 2, 1, 5}, n2[] = {9, 8, 1, 0, 1, 9, 4, 0, 4, 1}; + printf("%d\n", maxWidthRamp(n1, ARRAY_SIZE(n1))); // expect: 4 + printf("%d\n", maxWidthRamp(n2, ARRAY_SIZE(n2))); // expect: 7 +} diff --git a/maximum_width_ramp.py b/maximum_width_ramp.py @@ -0,0 +1,30 @@ +# 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 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 +""" + + +class Solution(object): + def maxWidthRamp(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + stack, ans = [], 0 + for i, j in enumerate(nums): + if not stack or nums[stack[-1]] > j: + stack.append(i) + for i in range(len(nums))[::-1]: + while stack and nums[stack[-1]] <= nums[i]: + ans = max(ans, i - stack.pop()) + return ans + + +if __name__ == "__main__": + obj = Solution() + print(obj.maxWidthRamp(nums=[6, 0, 8, 2, 1, 5])) + print(obj.maxWidthRamp(nums=[9, 8, 1, 0, 1, 9, 4, 0, 4, 1]))