aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-06-15 19:50:24 -0600
committerJack Sangdahl <[email protected]>2025-06-15 19:50:24 -0600
commitea099f773c6117b6d9b3b133b527d169ccbb2de0 (patch)
tree6c940dd2333878ce9793335ca354a58e3b6661aa
parent31a6c4fe7350946add1ac40eba9ca7bc144714b6 (diff)
downloadleetcode-ea099f773c6117b6d9b3b133b527d169ccbb2de0.tar.gz
leetcode-ea099f773c6117b6d9b3b133b527d169ccbb2de0.zip
2016. maximum difference between increasing elements
-rw-r--r--max_diff_between_incr_elem.c25
-rw-r--r--max_diff_between_incr_elem.py28
2 files changed, 53 insertions, 0 deletions
diff --git a/max_diff_between_incr_elem.c b/max_diff_between_incr_elem.c
new file mode 100644
index 0000000..bf35ab0
--- /dev/null
+++ b/max_diff_between_incr_elem.c
@@ -0,0 +1,25 @@
+// 2016. Maximum Difference Between Increasing Elements
+#include "leetcode.h"
+
+/*
+ * given a 0-indexed integer array 'nums' of size 'n', find the maximum
+ * difference between 'nums[i]' and 'nums[j]' (ie. 'nums[j] - nums[i]') such
+ * that '0 <= i < j < n' and 'nums[i] < nums[j]'. return the maximum difference.
+ * if no such 'i' and 'j' exist, return -1
+ */
+
+int maximumDifference(int *nums, int numsSize) {
+ int min = nums[0], ans = -1;
+ for (int i = 1; i < numsSize; ++i) {
+ ans = fmax(ans, nums[i] - min);
+ min = fmin(min, nums[i]);
+ }
+ return ans;
+}
+
+int main() {
+ int n1[] = {7, 1, 5, 4}, n2[] = {9, 4, 3, 2}, n3[] = {1, 5, 2, 10};
+ printf("%d\n", maximumDifference(n1, ARRAY_SIZE(n1))); // expect: 4
+ printf("%d\n", maximumDifference(n2, ARRAY_SIZE(n2))); // expect: -1
+ printf("%d\n", maximumDifference(n3, ARRAY_SIZE(n3))); // expect: 9
+}
diff --git a/max_diff_between_incr_elem.py b/max_diff_between_incr_elem.py
new file mode 100644
index 0000000..d277298
--- /dev/null
+++ b/max_diff_between_incr_elem.py
@@ -0,0 +1,28 @@
+# 2016. Maximum Difference Between Increasing Elements
+
+"""
+given a 0-indexed integer array 'nums' of size 'n', find the maximum
+difference between 'nums[i]' and 'nums[j]' (ie. 'nums[j] - nums[i]') such
+that '0 <= i < j < n' and 'nums[i] < nums[j]'. return the maximum difference.
+if no such 'i' and 'j' exist, return -1
+"""
+
+
+class Solution(object):
+ def maximumDifference(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ minn, ans = nums[0], -1
+ for i in range(len(nums)):
+ ans = max(ans, nums[i] - minn)
+ minn = min(minn, nums[i])
+ return ans if ans != 0 else -1
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.maximumDifference(nums=[7, 1, 5, 4]))
+ print(obj.maximumDifference(nums=[9, 4, 3, 2]))
+ print(obj.maximumDifference(nums=[1, 5, 2, 10]))