aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2024-10-09 22:02:23 -0600
committerJack Sangdahl <[email protected]>2024-10-09 22:02:23 -0600
commit7187348d45fa427319707488e5affe5d5b97f708 (patch)
tree898b52228c09c64457f42c172b6578505ed1036c
parent0bc0cb90d1af8a72f45dfe7fe93025c368a2790d (diff)
downloadleetcode-7187348d45fa427319707488e5affe5d5b97f708.tar.gz
leetcode-7187348d45fa427319707488e5affe5d5b97f708.zip
962. maximum width ramp
-rw-r--r--maximum_width_ramp.c33
-rw-r--r--maximum_width_ramp.py30
2 files changed, 63 insertions, 0 deletions
diff --git a/maximum_width_ramp.c b/maximum_width_ramp.c
new file mode 100644
index 0000000..284fc8f
--- /dev/null
+++ 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
new file mode 100644
index 0000000..8d49c62
--- /dev/null
+++ 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]))