question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
longest-non-decreasing-subarray-from-two-arrays
|
Solving Maximum Length of Non-Decreasing Subsequences using DP
|
solving-maximum-length-of-non-decreasing-7eey
|
Finding the Maximum Length of Non-Decreasing Subsequences\n\n## Overview\n\nThis article explains a solution to find the maximum length of a non-decreasing subs
|
Nikhil-Mhatre
|
NORMAL
|
2024-08-17T19:23:30.941659+00:00
|
2024-08-17T19:23:30.941684+00:00
| 13 | false |
# Finding the Maximum Length of Non-Decreasing Subsequences\n\n## Overview\n\nThis article explains a solution to find the maximum length of a non-decreasing subsequence from two lists of integers. The approach uses dynamic programming to handle the problem efficiently.\n\n## Problem Statement\n\nGiven two lists, `nums1` and `nums2`, of the same length, the task is to determine the maximum length of a non-decreasing subsequence that can be formed by choosing elements from either `nums1` or `nums2` while maintaining the order of indices.\n\n## Approach\n\nThe solution uses dynamic programming to keep track of the maximum length of non-decreasing subsequences that end with elements from `nums1` and `nums2`. \n\n### Dynamic Programming Table\n\nWe define a 2D array `dp` where:\n- `dp[i][0]` represents the maximum length of a non-decreasing subsequence ending with `nums1[i]`.\n- `dp[i][1]` represents the maximum length of a non-decreasing subsequence ending with `nums2[i]`.\n\n### Initialization\n\nThe table `dp` is initialized as follows:\n- Each entry in `dp` starts with a value of `1` because a single element alone is a valid non-decreasing subsequence.\n\n### Transition\n\nFor each index `i` from `1` to `n-1`, the table is updated based on the following conditions:\n- **For `dp[i][0]`** (ending with `nums1[i]`):\n - If `nums1[i] >= nums1[i-1]`, then `dp[i][0]` can be extended from `dp[i-1][0]`.\n - If `nums1[i] >= nums2[i-1]`, then `dp[i][0]` can also be extended from `dp[i-1][1]`.\n- **For `dp[i][1]`** (ending with `nums2[i]`):\n - If `nums2[i] >= nums1[i-1]`, then `dp[i][1]` can be extended from `dp[i-1][0]`.\n - If `nums2[i] >= nums2[i-1]`, then `dp[i][1]` can also be extended from `dp[i-1][1]`.\n\nAfter processing each index `i`, the maximum length found so far is updated.\n\n\n# Code\n```\nfrom typing import List\n\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n if not nums1 or not nums2:\n return 0\n n = len(nums1)\n if n == 1:\n return 1\n \n # dp[i][0] - max length of non-decreasing sequence ending with nums1[i]\n # dp[i][1] - max length of non-decreasing sequence ending with nums2[i]\n dp = [[1] * 2 for _ in range(n)]\n maxlen = 1\n \n for i in range(1, n):\n # Check if nums1[i] can continue a sequence ending with nums1[i-1]\n if nums1[i] >= nums1[i-1]:\n dp[i][0] = dp[i-1][0] + 1\n # Check if nums1[i] can continue a sequence ending with nums2[i-1]\n if nums1[i] >= nums2[i-1]:\n dp[i][0] = max(dp[i][0], dp[i-1][1] + 1)\n \n # Check if nums2[i] can continue a sequence ending with nums1[i-1]\n if nums2[i] >= nums1[i-1]:\n dp[i][1] = dp[i-1][0] + 1\n # Check if nums2[i] can continue a sequence ending with nums2[i-1]\n if nums2[i] >= nums2[i-1]:\n dp[i][1] = max(dp[i][1], dp[i-1][1] + 1)\n \n # Update the maximum length found so far\n maxlen = max(maxlen, dp[i][0], dp[i][1])\n \n return maxlen\n\n```
| 0 | 0 |
['Python3']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
dfs + dp, O(n) time and space
|
dfs-dp-on-time-and-space-by-hershyz-19se
|
Code\n\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n\n @cache\n def dfs(index, choice):\n\n
|
hershyz
|
NORMAL
|
2024-07-23T07:02:34.090340+00:00
|
2024-07-23T07:02:34.090370+00:00
| 22 | false |
# Code\n```\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n\n @cache\n def dfs(index, choice):\n\n # base case, we reached the end\n if index == len(nums1) - 1:\n return 1 \n \n # if we were asked to choose nums1[index] at this index\n if choice == 1:\n res = 1\n if nums1[index] <= nums1[index + 1]:\n res = max(res, 1 + dfs(index + 1, 1))\n if nums1[index] <= nums2[index + 1]:\n res = max(res, 1 + dfs(index + 1, 2))\n return res\n\n # if we were asked to choose nums2[index] at this index\n if choice == 2:\n res = 1\n if nums2[index] <= nums1[index + 1]:\n res = max(res, 1 + dfs(index + 1, 1))\n if nums2[index] <= nums2[index + 1]:\n res = max(res, 1 + dfs(index + 1, 2))\n return res\n\n # in either case, the minimum non-decreasing subarray we could get from that point was length 1\n # if the following indices were possible to continue the non-decreasing subarray, we try\n \n # call dfs\n res = 1\n for i in range(len(nums1)):\n res = max(res, dfs(i, 1))\n res = max(res, dfs(i, 2))\n return res\n```
| 0 | 0 |
['Python3']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
DP. Time O(n). Space O(1)
|
dp-time-on-space-o1-by-xxxxkav-zh8f
|
\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n dp1, dp2, ans = 1, 1, 1\n for (prev_n1, n1),
|
xxxxkav
|
NORMAL
|
2024-07-12T21:18:18.629380+00:00
|
2024-07-12T21:19:16.444950+00:00
| 20 | false |
```\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n dp1, dp2, ans = 1, 1, 1\n for (prev_n1, n1), (prev_n2, n2) in zip(pairwise(nums1), pairwise(nums2)):\n dp1, dp2 = (max(dp1 if n1 >= prev_n1 else 0, dp2 if n1 >= prev_n2 else 0) + 1, \n max(dp2 if n2 >= prev_n2 else 0, dp1 if n2 >= prev_n1 else 0) + 1) \n ans = max(dp1, dp2, ans)\n return ans \n```
| 0 | 0 |
['Dynamic Programming', 'Python3']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
cpp O(1)
|
cpp-o1-by-deshmukhrao-o283
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
DeshmukhRao
|
NORMAL
|
2024-07-12T05:38:37.795715+00:00
|
2024-07-12T05:38:37.795755+00:00
| 0 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {\n int prevCount1 = 1, prevCount2 = 1;\n int maxLen = 1;\n\n for (int i = 1; i < nums1.size(); i++) {\n int currCount1 = 1, currCount2 = 1;\n \n if (nums1[i] >= nums1[i - 1]) {\n currCount1 = max(currCount1, prevCount1 + 1);\n }\n if (nums1[i] >= nums2[i - 1]) {\n currCount1 = max(currCount1, prevCount2 + 1);\n }\n if (nums2[i] >= nums2[i - 1]) {\n currCount2 = max(currCount2, prevCount2 + 1);\n }\n if (nums2[i] >= nums1[i - 1]) {\n currCount2 = max(currCount2, prevCount1 + 1);\n }\n \n maxLen = max(maxLen, max(currCount1, currCount2));\n prevCount1 = currCount1;\n prevCount2 = currCount2;\n }\n \n return maxLen;\n }\n};\n\n```
| 0 | 0 |
['C++']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Typescript clean solution
|
typescript-clean-solution-by-codingtorna-i5yc
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
CodingTornado
|
NORMAL
|
2024-07-10T16:21:43.247785+00:00
|
2024-07-10T16:21:43.247815+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunction maxNonDecreasingLength(nums1: number[], nums2: number[]): number {\n let prev1 = 1\n let prev2 = 1\n let max = 1\n for(let i = 1; i < nums1.length; i++){\n // Compute num1\n let use1 = nums1[i] >= nums1[i-1] ? prev1 + 1 : 1\n let use2 = nums1[i] >= nums2[i-1] ? prev2 + 1 : 1\n const curr1 = Math.max(use1, use2)\n\n // Compute num2\n use1 = nums2[i] >= nums1[i-1] ? prev1 + 1 : 1\n use2 = nums2[i] >= nums2[i-1] ? prev2 + 1 : 1\n const curr2 = Math.max(use1, use2)\n prev1 = curr1\n prev2 = curr2\n max = Math.max(max, curr1, curr2)\n }\n return max\n};\n```
| 0 | 0 |
['TypeScript']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Java simple 9 liner - no DP O(1) space; beats 96%
|
java-simple-9-liner-no-dp-o1-space-beats-c6gv
|
Intuition\nHave 2 variables l1 and l2 track the length of longest non-decreasing subarray ending at nums1 and nums2 respectively.\n\nAt each index i, we can upd
|
pathikritbhowmick
|
NORMAL
|
2024-06-05T17:51:20.422279+00:00
|
2024-06-05T17:51:20.422310+00:00
| 7 | false |
# Intuition\nHave 2 variables `l1` and `l2` track the length of longest non-decreasing subarray ending at `nums1` and `nums2` respectively.\n\nAt each index `i`, we can update `l1` as follows:\n- If `nums1[i-1] <= nums1[i]` then `l1 + 1` \n- If `nums2[i-1] <= nums1[i]` then `l2 + 1`\n- else `1` (start a new subarray with `nums1[i]`)\n- Take max of all of above\n\nWe can do similar for `l2` and then track the max of `l1` and `l2` as the answer\n\n# Complexity\n- Time complexity: `O(n)`\n\n- Space complexity: `O(1)`\n\n# Code\n```\nimport static java.lang.Math.max;\n\nclass Solution { \n public int maxNonDecreasingLength(int[] nums1, int[] nums2) { \n int l1 = 1, l2 = 1, ans = 1; \n for(int i = 1; i < nums1.length; i++){\n int t11 = nums1[i-1] <= nums1[i] ? l1 + 1 : 1;\n int t12 = nums1[i-1] <= nums2[i] ? l1 + 1 : 1;\n int t21 = nums2[i-1] <= nums1[i] ? l2 + 1 : 1;\n int t22 = nums2[i-1] <= nums2[i] ? l2 + 1 : 1;\n ans = max(ans, max(l1 = max(t11, t21), l2 = max(t12, t22)));\n }\n return ans;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
No Kadanes Algo simple DP
|
no-kadanes-algo-simple-dp-by-deshmukhrao-gwiz
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nsee solution\n https://youtu.be/vfZ34E7k7MI?feature=shared\n\n# Complexit
|
DeshmukhRao
|
NORMAL
|
2024-05-27T17:17:18.805296+00:00
|
2024-05-27T17:17:18.805322+00:00
| 4 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nsee solution\n https://youtu.be/vfZ34E7k7MI?feature=shared\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {\n \n vector<int> dp1(nums1.size(),1);\n vector<int> dp2(nums2.size(),1);\n \n for(int i=1;i<nums1.size();i++){\n if(nums1[i]>=nums1[i-1]){\n dp1[i]=max(dp1[i],dp1[i-1]+1);\n }\n if(nums1[i]>=nums2[i-1]){\n dp1[i]=max(dp1[i],dp2[i-1]+1);\n }\n if(nums2[i]>=nums2[i-1]){\n dp2[i]=max(dp2[i],dp2[i-1]+1);\n }\n if(nums2[i]>=nums1[i-1]){\n dp2[i]=max(dp2[i],dp1[i-1]+1);\n }\n }\n \n return max(*max_element(dp1.begin(),dp1.end()),*max_element(dp2.begin(),dp2.end()));\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Geady Rolling window c++ O(1) memory
|
geady-rolling-window-c-o1-memory-by-math-fdbt
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
mathpag
|
NORMAL
|
2024-05-26T01:20:43.371611+00:00
|
2024-05-26T01:20:43.371629+00:00
| 0 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {\n int n = nums1.size();\n int max_length = 1;\n int l = 0, h = 1;\n int last_max_start = -1;\n int curr = min(nums2[0], nums1[0]);\n while(h < n){\n int next_min = nums1[h];\n int next_max = nums2[h];\n if(next_min > next_max) swap(next_min, next_max);\n if(next_min >= curr){\n last_max_start = -1;\n max_length = max(max_length, h - l + 1);\n curr = next_min;\n } else if(next_max >= curr) {\n if(last_max_start == -1)\n last_max_start = h;\n curr = next_max;\n max_length = max(max_length, h - l + 1);\n } else if( l < last_max_start){\n l = last_max_start;\n curr = min(nums1[last_max_start], nums2[last_max_start]);\n last_max_start = -1;\n h = l + 1;\n continue;\n } else{\n curr = next_min;\n l = h;\n }\n ++h;\n }\n\n return max_length;\n\n\n \n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Easy dp solution
|
easy-dp-solution-by-liew-li-tclp
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
liew-li
|
NORMAL
|
2024-05-23T14:10:49.631729+00:00
|
2024-05-23T14:10:49.631763+00:00
| 12 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nvar maxNonDecreasingLength = function(nums1, nums2) {\n const N = nums1.length;\n let dp0 = 1;\n let dp1 = 1\n let res = 1;\n for (let i = 1; i < N; ++i) {\n let v0 = 1;\n let v1 = 1;\n if (nums1[i] >= nums1[i - 1]) {\n v0 = 1 + dp0;\n }\n if (nums1[i] >= nums2[i - 1]) {\n v0 = Math.max(v0, dp1 + 1);\n }\n\n if (nums2[i] >= nums1[i - 1]) {\n v1 = 1 + dp0;\n }\n if (nums2[i] >= nums2[i - 1]) {\n v1 = Math.max(v1, 1 + dp1);\n }\n [dp0, dp1] = [v0, v1];\n res = Math.max(res, dp0, dp1);\n }\n return res;\n};\n```
| 0 | 0 |
['JavaScript']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Python 3 - Dynamic Programming + Explanation
|
python-3-dynamic-programming-explanation-kvry
|
We need to keep two arrays that constitute the longest path if we choose either nums1 or nums2 for each i in the range(1, n). Rather than storing the actual num
|
amronagdy
|
NORMAL
|
2024-05-12T10:04:39.721688+00:00
|
2024-05-12T10:04:39.721711+00:00
| 17 | false |
We need to keep two arrays that constitute the longest path if we choose either `nums1` or `nums2` for each `i` in the `range(1, n)`. Rather than storing the actual numbers chosen, we can just keep track of how long that longest path is, this is what we store in `dp1` and `dp2`, where each represents the length ending at `i` if we choose `nums1[i]` or `nums2[i]` respectively.\n\nWe have to update both `dp` arrays for each `i`, where we ask ourselves: "could we continue the longest decreasing subsequence by staying on the current `nums` (`a` and `b` in the method `__calculate_dp` can represent either `1` or `2`, depending on the way they are passed in to the method), or could we switch over from the other `nums` and form a longer subsequence?".\n\nAt the end of each iteration, we update `max_length` with the new longest path value.\n```\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n\n # Initialize DP arrays to store the length of the non-decreasing subarray at index i.\n # dp1[i] represents the length ending at i using nums1[i]\n # dp2[i] represents the length ending at i using nums2[i]\n dp1 = [1] * n\n dp2 = [1] * n\n\n max_length = 1\n\n for i in range(1, n):\n Solution.__calculate_dp(nums1, nums2, dp1, dp2, i)\n Solution.__calculate_dp(nums2, nums1, dp2, dp1, i)\n \n max_length = max(max_length, dp1[i], dp2[i])\n\n return max_length\n\n @staticmethod\n def __calculate_dp(\n nums_a: List[int],\n nums_b: List[int],\n dp_a: List[int],\n dp_b: List[int],\n i: int\n ) -> None:\n """\n For each stage of the iteration, at index i we ask ourselves could we continue\n the longest decreasing subsequence by staying on nums_a or switching over from nums_b?\n """\n # If we stay on nums_a, is it still a non-decreasing subarray.\n if nums_a[i] >= nums_a[i - 1]:\n dp_a[i] = dp_a[i - 1] + 1\n\n # If we were to swap over to nums_a from nums_b and have it still form a non-decreasing subarray,\n # would this be a longer subarray than if we had stayed on nums_a?\n if nums_a[i] >= nums_b[i - 1]:\n dp_a[i] = max(dp_a[i], dp_b[i - 1] + 1)\n```
| 0 | 0 |
['Python3']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Dynamic programming | Tabulation
|
dynamic-programming-tabulation-by-rj_999-0wz8
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
rj_9999
|
NORMAL
|
2024-05-12T05:06:57.350680+00:00
|
2024-05-12T05:06:57.350705+00:00
| 3 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {\n vector<vector<int>>dp(nums1.size(),vector<int>(2,0));\n dp[0][0]=1;\n dp[0][1]=1;\n for(int i=1;i<nums1.size();i++){\n for(int j=0;j<2;j++){\n if(j==0){\n if(nums1[i]>=nums1[i-1] && nums1[i]>=nums2[i-1])dp[i][0]=max(1+dp[i-1][0],1+dp[i-1][1]);\n else if(nums1[i]>=nums1[i-1] && nums1[i]<nums2[i-1])dp[i][0]=1+dp[i-1][0];\n else if(nums1[i]<nums1[i-1] && nums1[i]>=nums2[i-1])dp[i][0]=1+dp[i-1][1];\n else if(nums1[i]<nums1[i-1] && nums1[i]<nums2[i-1])dp[i][0]=1;\n }\n else if(j==1){\n if(nums2[i]>=nums1[i-1] && nums2[i]>=nums2[i-1])dp[i][1]=max(1+dp[i-1][0],1+dp[i-1][1]);\n else if(nums2[i]>=nums1[i-1] && nums2[i]<nums2[i-1])dp[i][1]=1+dp[i-1][0];\n else if(nums2[i]<nums1[i-1] && nums2[i]>=nums2[i-1])dp[i][1]=1+dp[i-1][1];\n else if(nums2[i]<nums1[i-1] && nums2[i]<nums2[i-1])dp[i][1]=1;\n }\n }\n }\n int ans=0;\n for(int i=0;i<nums1.size();i++){\n for(int j=0;j<2;j++){\n ans=max(ans,dp[i][j]);\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['Array', 'Dynamic Programming', 'C++']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Easy DP
|
easy-dp-by-nishantd01-m0fn
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
nishantd01
|
NORMAL
|
2024-05-10T14:52:06.077519+00:00
|
2024-05-10T14:52:06.077541+00:00
| 3 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(2*N), N is size of array\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> dp;\n\n int solve(vector<int>& nums1, vector<int>& nums2, int idx, int arrayNum) {\n if (idx == nums1.size() - 1) {\n return 1;\n }\n\n if(dp[idx][arrayNum] != -1) {\n return dp[idx][arrayNum];\n }\n\n int v1 = nums1[idx];\n if (arrayNum == 1) {\n v1 = nums2[idx];\n }\n\n int nxt1 = nums1[idx + 1];\n int nxt2 = nums2[idx + 1];\n int first = 1;\n int second = 1;\n if (nxt1 >= v1) {\n first = 1 + solve(nums1, nums2, idx + 1, 0);\n }\n\n if (nxt2 >= v1) {\n second = 1 + solve(nums1, nums2, idx + 1, 1);\n }\n\n return dp[idx][arrayNum]=max(first,second);\n }\n\n int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {\n dp.resize(nums1.size(),vector<int>(2,-1));\n int maxVal = 1;\n for (int i = 0; i < nums1.size(); i++) {\n int first = solve(nums1, nums2, i, 0);\n int second = solve(nums1, nums2, i, 1);\n maxVal = max(maxVal, max(first, second));\n }\n\n return maxVal;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Dayyyyum how did they fit alll dat in O(1) BB ???? o.0
|
dayyyyum-how-did-they-fit-alll-dat-in-o1-flr3
|
Intuition\nO(n) Time\nO(1) Space\n\n# Code\n\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n n = len
|
robert961
|
NORMAL
|
2024-04-16T06:29:36.135726+00:00
|
2024-04-16T06:29:36.135758+00:00
| 12 | false |
# Intuition\nO(n) Time\nO(1) Space\n\n# Code\n```\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n opt1 = opt2 = res = 1\n\n for i in range(1, n):\n o1 = max(opt1+ 1 if nums1[i] >= nums1[i-1] else 1, opt2 + 1 if nums1[i]>= nums2[i-1] else 1)\n o2 = max(opt2+ 1 if nums2[i] >= nums2[i-1] else 1, opt1 + 1 if nums2[i]>= nums1[i-1] else 1)\n opt1, opt2 = o1, o2\n res = max(res, opt1, opt2)\n return res \n```
| 0 | 0 |
['Python3']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Python3 DP solution with explanation
|
python3-dp-solution-with-explanation-by-g1wap
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this solution is that whenever our current value is greater than o
|
WuWei8
|
NORMAL
|
2024-04-11T15:52:50.157833+00:00
|
2024-04-11T15:52:50.157858+00:00
| 15 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this solution is that whenever our current value is greater than or equal to the previous value, we extend the length of our non-decreasing subarray by 1. If our current value is smaller than the previous value, we need to restart the length count of our subarray by restarting from length 1. Since the smallest length of our array is 1 in this problem, the smallest non-decreasing subarray is 1. \n\nFor each current position i , we need to compare it to the value in the previous position of both arrays nums1 and nums2. This is because at current position, we need to know whether it is better to continue the previous subarray or restart the subarray from current position. \n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n N = len(nums1)\n res = pre1 = pre2 = 1\n\n def getLen(curArr, i, pre1, pre2):\n cur = 1\n if curArr[i] >= nums1[i - 1]:\n cur = pre1 + 1\n if curArr[i] >= nums2[i - 1]:\n cur = max(cur, pre2 + 1)\n\n return cur\n\n for i in range(1, N):\n tmp = pre1\n pre1 = getLen(nums1, i, pre1, pre2)\n pre2 = getLen(nums2, i, tmp, pre2)\n res = max(res, pre1, pre2)\n #print(f"i = {i} pre1 = {pre1} pre2 = {pre2} res = {res}")\n return res\n```
| 0 | 0 |
['Python3']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Python (Simple DP)
|
python-simple-dp-by-rnotappl-qdpr
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
rnotappl
|
NORMAL
|
2024-04-11T12:56:39.956137+00:00
|
2024-04-11T12:56:39.956190+00:00
| 10 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxNonDecreasingLength(self, nums1, nums2):\n n = len(nums1)\n\n @lru_cache(None)\n def dfs(i):\n if i == n:\n return 0,0 \n\n mx_1, mx_2 = 1, 1 \n\n if i+1 < n and nums1[i+1] >= nums1[i]:\n mx_1 = max(mx_1,1+dfs(i+1)[0])\n\n if i+1 < n and nums2[i+1] >= nums2[i]:\n mx_2 = max(mx_2,1+dfs(i+1)[1])\n\n if i+1 < n and nums1[i+1] >= nums2[i]:\n mx_2 = max(mx_2,1+dfs(i+1)[0])\n\n if i+1 < n and nums2[i+1] >= nums1[i]:\n mx_1 = max(mx_1,1+dfs(i+1)[1])\n\n return mx_1,mx_2\n\n return max(max([dfs(i)[0] for i in range(n)]),max([dfs(i)[1] for i in range(n)]))\n```
| 0 | 0 |
['Python3']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
C++ | easy DP | few lines | O(N)
|
c-easy-dp-few-lines-on-by-shubhamchandra-4dam
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\nl1 : length of increasing subsequence ending at nums1 i\nl2 : length of increasing su
|
shubhamchandra01
|
NORMAL
|
2024-04-09T08:12:19.117731+00:00
|
2024-04-09T08:13:07.028213+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nl1 : length of increasing subsequence ending at nums1 i\nl2 : length of increasing subsequence ending at nums2 i\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {\n\t\tint l1 = 1, l2 = 1, ans = 1;\n\t\tint n = nums1.size();\n\t\tfor (int i = 1; i < n; i++) {\n\t\t\tint curL1 = 1, curL2 = 1;\n\t\t\tif (nums1[i - 1] <= nums1[i])\n\t\t\t\tcurL1 = 1 + l1;\n\t\t\tif (nums2[i - 1] <= nums1[i])\n\t\t\t\tcurL1 = max(curL1, 1 + l2);\n\t\t\tif (nums1[i - 1] <= nums2[i]) \n\t\t\t\tcurL2 = 1 + l1;\n\t\t\tif (nums2[i - 1] <= nums2[i]) \n\t\t\t\tcurL2 = max(curL2, 1 + l2);\n\t\t\tl1 = curL1, l2 = curL2;\n\t\t\tans = max({ans, l1, l2});\n\t\t} \n\t\treturn ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
DP solution || Clearly Explained || T/M: 92.7% / 98.6%
|
dp-solution-clearly-explained-tm-927-986-5yzj
|
Intuition\n Describe your first thoughts on how to solve this problem. \nWhen initially approaching this problem, consider these key points.\n\n- You can choose
|
nayajueun
|
NORMAL
|
2024-04-07T15:18:02.143743+00:00
|
2024-04-08T03:17:00.348497+00:00
| 32 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen initially approaching this problem, consider these key points.\n\n- You can choose from two different arrays at each step.\n- A non-decreasing subarray means each element is equal to or larger than the preceding element.\n- Your choice at index `i` will affect the potential length of the non-decreasing subarray that ends at index `i + 1`.\n\nGiven these, dynamic programming would be the go-to strategy for this problem because in every index, every decision is made based on earlier decisions. Hence, it efficiently navigates through overlapping choices at each step and builds upon smaller, proviously solved protions to find the optimal, to ensure optimal decisions made at every index by reusing earlier calculations.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n## Dynamic programming setup:\n\nState Definition:\n\n- `dp1[i]`: Represents the length of the longest non-decreasing subarray ending at index i when the element from nums1[i] is chosen.\n- `dp2[i]`: Represents the length of the longest non-decreasing subarray ending at index i when the element from nums2[i] is chosen.\n\nBase Case:\n\n- At index `0`, there are no previous elements to compare with, so the longest non-decreasing subarray for both `dp1` and `dp2` is simply the first element itself.\n- `dp1[0] = 1`\n- `dp2[0] = 1`\n\nRecursive relation:\n\nFor each `i`:\n\n1. For `dp1[i]`\n - If `nums1[i]` is non-decreasing with respect to both `nums1[i-1]` and `nums2[i-1]`, then `dp1[i]` is the maximum length of either subarray up to i-1 plus one.\n - If `nums1[i]` is non-decreasing only with respect to `nums1[i-1]`, then `dp1[i]` extends the subarray from `nums1` only.\n - If `nums1[i]` is non-decreasing only with respect to `nums2[i-1]`, then `dp1[i]` extends the subarray from `nums2` only.\n - If `nums1[i]` is not non-decreasing with respect to either, we start a new subarray, so `dp1[i]` is reset to 1.\n\n if nums1[i] >= nums1[i - 1] and nums1[i] >= nums2[i - 1]:\n curr1 = max(prev_curr1 + 1, prev_curr2 + 1)\n elif nums1[i] >= nums1[i - 1]:\n curr1 = prev_curr1 + 1\n elif nums1[i] >= nums2[i - 1]:\n curr1 = prev_curr2 + 1\n else:\n curr1 = 1\n\n2. For `dp2[i]`\n - Similar rules applied.\n\n if nums2[i] >= nums1[i - 1] and nums2[i] >= nums2[i - 1]:\n curr2 = max(prev_curr1 + 1, prev_curr2 + 1)\n elif nums2[i] >= nums2[i - 1]:\n curr2 = prev_curr2 + 1\n elif nums2[i] >= nums1[i - 1]:\n curr2 = prev_curr1 + 1\n else:\n curr2 = 1\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$ for space-optimized code as below.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n # dp1[i] = longest non-decreasing subarray ending at i with nums1[i]\n # dp2[i] = longest non-decreasing subarray ending at i with nums2[i]\n\n n = len(nums1)\n curr1 = 1\n curr2 = 1\n ans = 1\n for i in range(1, n):\n\n prev_curr1 = curr1\n prev_curr2 = curr2\n\n if nums1[i] >= nums1[i - 1] and nums1[i] >= nums2[i - 1]:\n curr1 = max(prev_curr1 + 1, prev_curr2 + 1)\n elif nums1[i] >= nums1[i - 1]:\n curr1 = prev_curr1 + 1\n elif nums1[i] >= nums2[i - 1]:\n curr1 = prev_curr2 + 1\n else:\n curr1 = 1\n \n if nums2[i] >= nums1[i - 1] and nums2[i] >= nums2[i - 1]:\n curr2 = max(prev_curr1 + 1, prev_curr2 + 1)\n elif nums2[i] >= nums2[i - 1]:\n curr2 = prev_curr2 + 1\n elif nums2[i] >= nums1[i - 1]:\n curr2 = prev_curr1 + 1\n else:\n curr2 = 1\n ans = max(ans, curr1, curr2)\n\n return ans\n\n```
| 0 | 0 |
['Dynamic Programming', 'Python', 'Python3']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
C++/Python, dynamic programming solution with explanation
|
cpython-dynamic-programming-solution-wit-x6f2
|
dp[i][0] is max size of Longest Non-decreasing Subarray when we select nums1[i].\ndp[i][1] is max size of Longest Non-decreasing Subarray when we select nums2[i
|
shun6096tw
|
NORMAL
|
2024-03-11T06:23:14.597381+00:00
|
2024-03-11T06:23:14.597417+00:00
| 2 | false |
dp[i][0] is max size of Longest Non-decreasing Subarray when we select nums1[i].\ndp[i][1] is max size of Longest Non-decreasing Subarray when we select nums2[i].\n\nAt first,\ndp[0][0] = dp[0][1] = 1, there is only one element in the nums3.\n\nAnd to determine nums3[i],\nand should check if nums1[i] >= nums1[i-1] and nums1[i] >= nums2[i-1],\nalso nums2[i] >= nums1[i-1] and nums2[i] >= nums2[i-1].\n\ndp[i][0] = 1 + max(dp[i-1][0] if nums1[i] >= nums1[i-1] else 0, dp[i-1][1] if nums1[i] >= nums2[i-1] else 0)\ndp[i][1] = 1 + max(dp[i-1][0] if nums2[i] >= nums1[i-1] else 0, dp[i-1][1] if nums2[i] >= nums2[i-1] else 0)\n\ntc is O(n), sc is O(1)\n### python\n```python\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n ans = 0\n dp_0 = dp_1 = 0\n for i, (x, y) in enumerate(zip(nums1, nums2)):\n cur_0 = 1 + max(dp_0 if i and x >= nums1[i-1] else 0, dp_1 if i and x >= nums2[i-1] else 0)\n cur_1 = 1 + max(dp_0 if i and y >= nums1[i-1] else 0, dp_1 if i and y >= nums2[i-1] else 0)\n dp_0, dp_1 = cur_0, cur_1\n ans = max(ans, dp_0, dp_1)\n return ans\n```\n### c++\n```cpp\nclass Solution {\npublic:\n int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {\n int dp_0 = 1, dp_1 = 1, ans = 1;\n for (int i = 1, cur_0, cur_1; i < nums1.size(); i+=1) {\n cur_0 = 1 + max(nums1[i] >= nums1[i-1]? dp_0:0, nums1[i] >= nums2[i-1]?dp_1:0);\n cur_1 = 1 + max(nums2[i] >= nums1[i-1]? dp_0:0, nums2[i] >= nums2[i-1]?dp_1:0);\n dp_0 = cur_0, dp_1 = cur_1;\n ans = max(ans, max(dp_0, dp_1));\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['Dynamic Programming', 'C', 'Python']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
C++ | Easy and Simple
|
c-easy-and-simple-by-pseudocode_lc-fdxm
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
Pseudocode_lc
|
NORMAL
|
2024-03-07T15:47:17.209407+00:00
|
2024-03-07T15:47:17.209438+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n \n int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {\n int n=nums1.size();\n vector<vector<int>> dp(n,vector<int>(2,1));\n int ans=1;\n for(int i=1;i<n;i++){\n if(nums1[i]>=nums1[i-1])dp[i][0]=max(dp[i][0],dp[i-1][0]+1);\n if(nums1[i]>=nums2[i-1])dp[i][0]=max(dp[i][0],dp[i-1][1]+1);\n if(nums2[i]>=nums1[i-1])dp[i][1]=max(dp[i][1],dp[i-1][0]+1);\n if(nums2[i]>=nums2[i-1])dp[i][1]=max(dp[i][1],dp[i-1][1]+1);\nans=max({dp[i][0],dp[i][1],ans});\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['Dynamic Programming', 'C++']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
✅ Explained: Only 6 line logic, O(n) time and O(1) space
|
explained-only-6-line-logic-on-time-and-tvamo
|
Intuition\n Describe your first thoughts on how to solve this problem. \nSince we\'re dealing with subarrays (not subsequences), we would anyways look at the ex
|
amartyabh
|
NORMAL
|
2024-03-04T20:36:30.819653+00:00
|
2024-03-04T20:36:30.819676+00:00
| 3 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince we\'re dealing with subarrays (not subsequences), we would anyways look at the exact prev value for length computation. Hence, we can use a variable to keep track of length, instead of maintaining an array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAt any index i,\n- lenSoFar1 = length so far till nums1[i - 1]\n- lenSoFar2 = length so far till nums2[i - 1]\n- newLen1 = length so far till nums1[i]\n- newLen2 = length so far till nums2[i]\n\nInitial values of all the above are 1. (since a subarray will have at least 1 element)\n\nCheck if nums1[i] can be placed after nums1[i - 1]. If yes, update newLen1. Then check if nums1[i] can be placed after nums2[i - 1]. If yes, in order to have the maximum length, we need to decide whether to follow nums1[i - 1] or nums2[i - 2]. Therefore, we check if 1 + lenSoFar2 > newLen1, only then we update newLen1. Repeat the same for nums2[i].\n\nThen update maxLen with the maximum of newLen1 and newLen2. Also, update lenSoFar1 and lenSoFar2 before entering the next pass of the for loop.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) excluding input\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxNonDecreasingLength(vector<int>& nums1, vector<int>& nums2) {\n int n = nums1.size();\n int maxLen = 1;\n int lenSoFar1 = 1, lenSoFar2 = 1;\n\n for (int i = 1; i < n; i++) {\n int newLen1 = 1;\n if (nums1[i] >= nums1[i - 1]) newLen1 = 1 + lenSoFar1;\n if (nums1[i] >= nums2[i - 1] && 1 + lenSoFar2 > newLen1) newLen1 = 1 + lenSoFar2;\n\n int newLen2 = 1;\n if (nums2[i] >= nums2[i - 1]) newLen2 = 1 + lenSoFar2;\n if (nums2[i] >= nums1[i - 1] && 1 + lenSoFar1 > newLen2) newLen2 = 1 + lenSoFar1;\n\n lenSoFar1 = newLen1, lenSoFar2 = newLen2;\n maxLen = max(maxLen, max(lenSoFar1, lenSoFar2));\n }\n\n return maxLen;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Simple Java solution
|
simple-java-solution-by-varshaagarwal111-r8dn
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
varshaagarwal11193
|
NORMAL
|
2024-03-04T16:05:23.862477+00:00
|
2024-03-04T16:05:23.862506+00:00
| 8 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public int maxNonDecreasingLength(int[] nums1, int[] nums2) {\n int n = nums1.length;\n int count1[] = new int[n];\n int count2[] = new int[n];\n count1[n-1]=1;\n count2[n-1]=1;\n int max = 1;\n for(int i=n-2;i>=0;i--) {\n count1[i] = 1;\n count2[i] = 1;\n if(nums1[i]<=nums1[i+1]){\n count1[i]=count1[i+1]+1;\n }\n if(nums1[i]<=nums2[i+1]){\n count1[i]=Math.max(count2[i+1]+1, count1[i]);\n }\n\n if(nums2[i]<=nums1[i+1]){\n count2[i]=count1[i+1]+1;\n }\n if(nums2[i]<=nums2[i+1]){\n count2[i]=Math.max(count2[i+1]+1, count2[i]);\n }\n //System.out.println(count1[i]+" "+count2[i]);\n max = Math.max(max, Math.max(count1[i],count2[i]));\n }\n\n return max;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Easy to read DP: beats 93% and 83%
|
easy-to-read-dp-beats-93-and-83-by-david-d3lu
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
davidzedong
|
NORMAL
|
2024-02-20T17:17:32.879750+00:00
|
2024-02-20T17:17:32.879773+00:00
| 47 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n \n n = len(nums1)\n\n rep: int = 1\n\n current1: int = 1\n current2: int = 1\n\n for i in range(1, n):\n \n # update current 1\n cur1_cur1 = current1 + 1 if nums1[i] >= nums1[i-1] else 1\n cur1_cur2 = current2 + 1 if nums1[i] >= nums2[i-1] else 1\n\n # update current 2\n cur2_cur1 = current1 + 1 if nums2[i] >= nums1[i-1] else 1\n cur2_cur2 = current2 + 1 if nums2[i] >= nums2[i-1] else 1\n\n # update rep\n current1 = max(cur1_cur1, cur1_cur2)\n current2 = max(cur2_cur1, cur2_cur2)\n rep = max(max(current1, current2), rep)\n\n return rep\n\n\n \n```
| 0 | 0 |
['Dynamic Programming', 'Python3']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Dynamic Programming Approach
|
dynamic-programming-approach-by-saitejap-dit6
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this problem lies in recognizing that at each position i in the ar
|
saitejapeddi
|
NORMAL
|
2024-02-13T20:25:26.130060+00:00
|
2024-02-13T20:25:26.130085+00:00
| 7 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this problem lies in recognizing that at each position i in the arrays, we have a choice: we can either take the value from nums1[i] or nums2[i] for our nums3 array. The goal is to make these choices in such a way that maximizes the length of the longest non-decreasing subarray in nums3. Dynamic programming is suitable here because the decision at each position depends on the decisions made up to that point, and there are overlapping subproblems that can be solved once and reused.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Dynamic Programming State Definition:** Define a 2D DP array dp where dp[i][0] represents the length of the longest non-decreasing subarray ending at i using the element from nums1, and dp[i][1] represents the same but using the element from nums2.\n\n**Initialization:** Initialize dp[i][0] and dp[i][1] to 1 for all i, because a single element by itself forms a non-decreasing subarray of length 1.\n\n**Transition:** For each position i from 1 to n - 1, update dp[i][0] and dp[i][1] based on the following conditions:\n\nIf nums1[i] is greater than or equal to both nums1[i-1] and nums2[i-1], then dp[i][0] can be incremented by considering the longest subarray lengths ending at i-1 with elements from both arrays.\n\nSimilarly, update dp[i][1] if nums2[i] is greater than or equal to both nums1[i-1] and nums2[i-1].\n\nThe key is to choose the maximum length possible by considering both previous elements from nums1 and nums2.\n\n**Result:** After filling the DP table, the maximum length of the longest non-decreasing subarray in nums3 is the maximum value in the dp table.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) - The solution iterates through each element of the arrays nums1 and nums2 exactly once. The decisions at each step are made in constant time, leading to a linear time complexity.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) - The solution utilizes a 2D DP array of size 2n (since there are n positions and for each position, two choices are tracked). Therefore, the space complexity is linear in terms of the input size n.\n\n# Code\n```\nclass Solution(object):\n def maxNonDecreasingLength(self, nums1, nums2):\n """\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: int\n """\n n = len(nums1)\n # dp[i][0] represents the length of the longest non-decreasing subarray ending with nums1[i]\n # dp[i][1] represents the length of the longest non-decreasing subarray ending with nums2[i]\n dp = [[1 for _ in range(2)] for _ in range(n)]\n \n for i in range(1, n):\n # Update dp for nums1[i]\n if nums1[i] >= nums1[i-1]:\n dp[i][0] = max(dp[i][0], dp[i-1][0] + 1)\n if nums1[i] >= nums2[i-1]:\n dp[i][0] = max(dp[i][0], dp[i-1][1] + 1)\n \n # Update dp for nums2[i]\n if nums2[i] >= nums2[i-1]:\n dp[i][1] = max(dp[i][1], dp[i-1][1] + 1)\n if nums2[i] >= nums1[i-1]:\n dp[i][1] = max(dp[i][1], dp[i-1][0] + 1)\n \n # The maximum length of the longest non-decreasing subarray is the max value in dp\n max_length = max(max(row) for row in dp)\n return max_length\n\n\n\n```
| 0 | 0 |
['Python']
| 0 |
longest-non-decreasing-subarray-from-two-arrays
|
Simple python3 solutions | O(1) memory
|
simple-python3-solutions-o1-memory-by-ti-2bw1
|
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co
|
tigprog
|
NORMAL
|
2024-02-09T21:32:42.275318+00:00
|
2024-02-09T21:36:51.240329+00:00
| 109 | false |
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n prev_elems = (0, 0)\n prev_lengths = [0, 0]\n \n result = 0\n\n for elems in zip(nums1, nums2):\n current_lengths = [1, 1]\n for i, elem in enumerate(elems):\n for j, prev_elem in enumerate(prev_elems):\n if elem >= prev_elem:\n current_lengths[i] = max(current_lengths[i], prev_lengths[j] + 1)\n \n result = max(result, max(current_lengths))\n\n prev_elems = elems\n prev_lengths = current_lengths\n \n return result\n```\n``` python3 []\n# simpler solution without inner loops\n\nclass Solution:\n def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:\n prev_elems = (0, 0)\n prev_lengths = [0, 0]\n \n result = 0\n\n for a, b in zip(nums1, nums2):\n current_lengths = [1, 1]\n if a >= prev_elems[0]:\n current_lengths[0] = max(current_lengths[0], prev_lengths[0] + 1)\n if a >= prev_elems[1]:\n current_lengths[0] = max(current_lengths[0], prev_lengths[1] + 1)\n if b >= prev_elems[0]:\n current_lengths[1] = max(current_lengths[1], prev_lengths[0] + 1)\n if b >= prev_elems[1]:\n current_lengths[1] = max(current_lengths[1], prev_lengths[1] + 1)\n \n result = max(result, max(current_lengths))\n\n prev_elems = (a, b)\n prev_lengths = current_lengths\n \n return result\n\n```
| 0 | 0 |
['Dynamic Programming', 'Greedy', 'Python3']
| 1 |
maximum-difference-between-increasing-elements
|
121. Best Time to Buy and Sell Stock
|
121-best-time-to-buy-and-sell-stock-by-v-zz5n
|
The only difference from 121. Best Time to Buy and Sell Stock is that we need to return -1 if no profit can be made.\n\nC++\ncpp\nint maximumDifference(vector<i
|
votrubac
|
NORMAL
|
2021-09-26T05:24:00.147345+00:00
|
2021-10-01T18:18:19.936340+00:00
| 9,426 | false |
The only difference from [121. Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) is that we need to return `-1` if no profit can be made.\n\n**C++**\n```cpp\nint maximumDifference(vector<int>& nums) {\n int mn = nums[0], res = -1;\n for (int i = 1; i < nums.size(); ++i) {\n res = max(res, nums[i] - mn);\n mn = min(mn, nums[i]);\n }\n return res == 0 ? -1 : res;\n}\n```
| 123 | 6 |
[]
| 9 |
maximum-difference-between-increasing-elements
|
Python simple one pass solution
|
python-simple-one-pass-solution-by-tovam-27pk
|
Python :\n\n\ndef maximumDifference(self, nums: List[int]) -> int:\n\tmaxDiff = -1\n\n\tminNum = nums[0]\n\n\tfor i in range(len(nums)):\n\t\tmaxDiff = max(maxD
|
TovAm
|
NORMAL
|
2021-10-25T19:24:20.611864+00:00
|
2021-10-25T19:24:20.611896+00:00
| 4,510 | false |
**Python :**\n\n```\ndef maximumDifference(self, nums: List[int]) -> int:\n\tmaxDiff = -1\n\n\tminNum = nums[0]\n\n\tfor i in range(len(nums)):\n\t\tmaxDiff = max(maxDiff, nums[i] - minNum)\n\t\tminNum = min(minNum, nums[i])\n\n\treturn maxDiff if maxDiff != 0 else -1\n```\n\n**Like it ? please upvote !**
| 38 | 0 |
['Python', 'Python3']
| 3 |
maximum-difference-between-increasing-elements
|
[Java/Python 3] Time O(n) space O(1) codes w/ brief explanation and a similar problem.
|
javapython-3-time-on-space-o1-codes-w-br-9r7r
|
Similar Problem: 121. Best Time to Buy and Sell Stock\n\n----\n\nTraverse input, compare current number to the minimum of the previous ones. then update the max
|
rock
|
NORMAL
|
2021-09-26T04:05:02.543498+00:00
|
2021-09-26T07:16:36.050711+00:00
| 5,933 | false |
**Similar Problem:** [121. Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock)\n\n----\n\nTraverse input, compare current number to the minimum of the previous ones. then update the max difference.\n```java\n public int maximumDifference(int[] nums) {\n int diff = -1;\n for (int i = 1, min = nums[0]; i < nums.length; ++i) {\n if (nums[i] > min) {\n diff = Math.max(diff, nums[i] - min);\n }\n min = Math.min(min, nums[i]);\n }\n return diff;\n }\n```\n```python\n def maximumDifference(self, nums: List[int]) -> int:\n diff, mi = -1, math.inf\n for i, n in enumerate(nums):\n if i > 0 and n > mi:\n diff = max(diff, n - mi) \n mi = min(mi, n)\n return diff \n```
| 34 | 2 |
['Java', 'Python3']
| 7 |
maximum-difference-between-increasing-elements
|
Similar to Best Time to Buy and Sell Stock[C++]
|
similar-to-best-time-to-buy-and-sell-sto-o3xh
|
\nCredit-Subhanshu Babbar\nclass Solution {\npublic:\n int maximumDifference(vector<int>& prices) {\n int maxPro = 0;\n int minPrice = INT_MAX;\n
|
ATleastGiveTry
|
NORMAL
|
2021-09-26T04:03:28.324577+00:00
|
2021-12-26T07:14:22.433624+00:00
| 2,549 | false |
```\nCredit-Subhanshu Babbar\nclass Solution {\npublic:\n int maximumDifference(vector<int>& prices) {\n int maxPro = 0;\n int minPrice = INT_MAX;\n for(int i = 0; i < prices.size(); i++){\n minPrice = min(minPrice, prices[i]);\n maxPro = max(maxPro, prices[i] - minPrice);\n }\n if(maxPro==0) return -1;\n return maxPro;\n \n }\n};\n```
| 25 | 4 |
['C']
| 1 |
maximum-difference-between-increasing-elements
|
C++ Simple and Short Solution
|
c-simple-and-short-solution-by-yehudisk-58bx
|
\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int mn = nums[0], res = 0;\n for (int i = 1; i < nums.size(); i++) {
|
yehudisk
|
NORMAL
|
2021-09-30T08:39:47.461442+00:00
|
2021-09-30T08:39:47.461470+00:00
| 1,569 | false |
```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int mn = nums[0], res = 0;\n for (int i = 1; i < nums.size(); i++) {\n res = max(res, nums[i] - mn);\n mn = min(mn, nums[i]);\n }\n return res == 0 ? -1 : res;\n }\n};\n```\n**Like it? please upvote!**
| 13 | 0 |
['C']
| 2 |
maximum-difference-between-increasing-elements
|
C++ DP
|
c-dp-by-lzl124631x-b1mt
|
See my latest update in repo LeetCode\n## Solution 1. Brute force\n\ncpp\n// OJ: https://leetcode.com/problems/maximum-difference-between-increasing-elements/\n
|
lzl124631x
|
NORMAL
|
2021-09-26T05:08:17.718910+00:00
|
2021-09-26T19:44:02.724696+00:00
| 983 | false |
See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n## Solution 1. Brute force\n\n```cpp\n// OJ: https://leetcode.com/problems/maximum-difference-between-increasing-elements/\n// Author: github.com/lzl124631x\n// Time: O(N^2)\n// Space: O(1)\nclass Solution {\npublic:\n int maximumDifference(vector<int>& A) {\n int N = A.size(), ans = -1;\n for (int i = 0; i < N; ++i) {\n for (int j = i + 1; j < N; ++j) {\n if (A[i] < A[j]) ans = max(ans, A[j] - A[i]);\n }\n }\n return ans;\n }\n};\n```\n\n## Solution 2. DP\n\n```cpp\n// OJ: https://leetcode.com/problems/maximum-difference-between-increasing-elements/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n int maximumDifference(vector<int>& A) {\n int N = A.size(), ans = -1, mn = INT_MAX;\n for (int i = 0; i < N; ++i) {\n mn = min(mn, A[i]);\n if (A[i] > mn) ans = max(ans, A[i] - mn);\n }\n return ans;\n }\n};\n```
| 9 | 2 |
[]
| 1 |
maximum-difference-between-increasing-elements
|
Concise Java, 6 lines, O(n) time, O(1) space
|
concise-java-6-lines-on-time-o1-space-by-xq32
|
Do what the problem says. Keep track of index i such as a[i] = min of a[0...j]\n```java\n public int maximumDifference(int[] a) {\n int r = -1, i = 0;\n
|
climberig
|
NORMAL
|
2021-09-26T04:29:11.177474+00:00
|
2021-09-26T04:55:11.931181+00:00
| 852 | false |
Do what the problem says. Keep track of index ```i``` such as ```a[i] = min of a[0...j]```\n```java\n public int maximumDifference(int[] a) {\n int r = -1, i = 0;\n for (int j = 1; j < a.length; j++)\n if (a[i] < a[j])\n r = Math.max(r, a[j] - a[i]);\n else i = j;\n return r;\n }
| 9 | 1 |
[]
| 0 |
maximum-difference-between-increasing-elements
|
✅☑️ Beats 100% || Easiest Possible Solution || Beginner friendly
|
beats-100-easiest-possible-solution-begi-wknx
|
image.png\n\n# Intuition\nIterating through the list:\n\nFor each element i in the input list nums, the code checks whether i is less than or equal to the curre
|
sumit4199
|
NORMAL
|
2024-04-02T06:57:17.724863+00:00
|
2024-04-02T07:02:07.604369+00:00
| 842 | false |
image.png\n\n# Intuition\n**Iterating through the list:**\n\nFor each element i in the input list nums, the code checks whether i is less than or equal to the current minimum value minn.\n\nIf i is less than or equal to minn, it updates minn to i, effectively updating the minimum value seen so far.\n\nIf i is greater than minn, it calculates the difference between i and minn and checks if it is greater than the current maximum difference diff. If it is, diff is updated to this new maximum difference.\n\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# PYTHON 3\n```\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n minn = 1e9\n diff = -1\n for i in nums:\n if i <= minn:\n minn = i\n else:\n diff = max(diff,i-minn)\n return diff\n```\n\n# JAVA\n```\nclass Solution {\n public int maximumDifference(int[] nums) {\n int minn = Integer.MAX_VALUE;\n int diff = -1;\n for (int i : nums) {\n if (i <= minn) {\n minn = i;\n } else {\n diff = Math.max(diff, i - minn);\n }\n }\n return diff;\n }\n}\n```\n\n# CPP\n```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int minn = 1e9;\n int diff = -1;\n for (int i : nums) {\n if (i <= minn) {\n minn = i;\n } else {\n diff = max(diff, i - minn);\n }\n }\n return diff;\n }\n};\n
| 8 | 0 |
['Array', 'Math', 'Two Pointers', 'Python', 'C++', 'Java', 'Python3']
| 2 |
maximum-difference-between-increasing-elements
|
Javascript O(n) Solution
|
javascript-on-solution-by-ashish1323-usym
|
Brute Force 0(n^2)\n\nvar maximumDifference = function(nums) {\n var diff=-1\n for(let i=0;i<nums.length;i++){\n for(let j=i+1;j<nums.length;j++){\
|
Ashish1323
|
NORMAL
|
2021-09-26T06:41:57.647286+00:00
|
2021-09-26T06:41:57.647334+00:00
| 1,039 | false |
# Brute Force 0(n^2)\n```\nvar maximumDifference = function(nums) {\n var diff=-1\n for(let i=0;i<nums.length;i++){\n for(let j=i+1;j<nums.length;j++){\n if (nums[j]> nums[i]) diff=Math.max(nums[j]-nums[i],diff)\n }\n }\n return diff\n};\n```\n# DP 0(n)\n```\nvar maximumDifference = function(nums) {\n var min=Infinity\n var diff=-1\n for(i=0;i<nums.length;i++){\n min = Math.min(min,nums[i])\n diff=Math.max(diff,nums[i]-min)\n }\n return diff==0 ? -1 : diff\n};\n```\n\n\n
| 8 | 0 |
['Dynamic Programming', 'JavaScript']
| 1 |
maximum-difference-between-increasing-elements
|
Java | Easy Solution | 100 ms
|
java-easy-solution-100-ms-by-vrinda-mitt-ct6k
|
\nclass Solution {\n public int maximumDifference(int[] nums) {\n int min = nums[0];\n int diff = -1;\n \n for(int i=1; i<nums.le
|
vrinda-mittal
|
NORMAL
|
2022-06-29T07:17:55.539222+00:00
|
2022-06-29T07:17:55.539260+00:00
| 582 | false |
```\nclass Solution {\n public int maximumDifference(int[] nums) {\n int min = nums[0];\n int diff = -1;\n \n for(int i=1; i<nums.length; i++){\n if(nums[i] > min){\n diff = Math.max(diff, nums[i]-min);\n }else{\n min = nums[i];\n }\n }\n \n return diff;\n }\n}\n```
| 7 | 0 |
['Java']
| 1 |
maximum-difference-between-increasing-elements
|
[C++] : O(n) Time + O(1) space solution : Based on prefix minimum approach with explanation
|
c-on-time-o1-space-solution-based-on-pre-sr3q
|
INTIUTION\nVery staightforward idea -> to maximize the difference, we need to consider the minimum possible number till that point from start and max possible n
|
akshatsahu100
|
NORMAL
|
2021-10-08T16:53:23.058788+00:00
|
2021-10-08T16:53:47.670315+00:00
| 560 | false |
# **INTIUTION**\nVery staightforward idea -> to maximize the difference, we need to consider the minimum possible number till that point from start and max possible number from the end, right?\n\n# **IMPLEMENTATION**\nWe can maintain a global ans which we will keep maximizing as we move forward.\nWe will maintain a minimum variable which keep tracks on what minimum value has been encountered so far. \nAt every point while iteratng, we can check the difference of the value at that index with the minimum we have found till now and update the global answer we recieved so far.\n\n# **COMPLEXITY ANALYSIS**\n**Time Complexity** : O(n) // only one traversal has been made\n**Space Complexity**: O(1) // no additional space allocated (only 2 variables)\n\n\n# **WORKING CODE**\n\n```\nint maximumDifference(vector<int>& nums) {\n \n int premin = INT_MAX, ans = 0;\n \n for(int i = 0; i < nums.size(); i++){\n premin = min(premin, nums[i]);\n ans = max(ans, nums[i] - premin);\n }\n \n return ans == 0 ? -1 : ans; // if ans == 0 means we got no valid answer (decreasing array)\n }\n```\n\nPlease upvote if its of any help..\nCHEERS!!\nHappy Coding Guys...
| 7 | 1 |
['C', 'Prefix Sum']
| 1 |
maximum-difference-between-increasing-elements
|
Best Java Solution O(n) : 0ms
|
best-java-solution-on-0ms-by-rohan_21s-2lz8
|
Initiate & Declare min as the minimum integer possible.\n2. Traverse the array nums using either for-each loop or general for loop.\n3. Update min using Math.
|
rohan_21s
|
NORMAL
|
2021-11-09T08:55:26.781334+00:00
|
2021-11-09T08:55:26.781363+00:00
| 731 | false |
1. Initiate & Declare ```min``` as the minimum integer possible.\n2. Traverse the array ```nums``` using either ```for-each``` loop or general ```for``` loop.\n3. Update ```min``` using ```Math.min()``` comparing the ``` current element``` with the previous ```min```.\n4. Update ```maxDiff``` using ```Math.max()``` comparing (the difference of ``` current element``` and ```min``` ) with ```min```.\n5. If ```maxDiff == 0```, that means no such i and j exists, return -1.\n6. Else return maximum difference i.e ```maxDiff```.\n```\n public int maximumDifference(int[] nums) {\n int maxDiff = 0;\n int min = Integer.MAX_VALUE;\n \n for(int element : nums){\n min = Math.min(element,min);\n maxDiff = Math.max(element-min,maxDiff);\n }\n if(maxDiff == 0)\n return -1;\n\n return maxDiff;\n }\n```
| 6 | 0 |
[]
| 0 |
maximum-difference-between-increasing-elements
|
[Python3] prefix min
|
python3-prefix-min-by-ye15-dpfx
|
Please check out this commit for solutions of weekly 260. \n\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n ans = -1 \n
|
ye15
|
NORMAL
|
2021-09-26T04:04:33.258105+00:00
|
2021-09-27T19:16:42.482187+00:00
| 1,146 | false |
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/fa0bb65b4cb428452e2b4192ad53e56393b8fb8d) for solutions of weekly 260. \n```\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n ans = -1 \n prefix = inf\n for i, x in enumerate(nums): \n if i and x > prefix: ans = max(ans, x - prefix)\n prefix = min(prefix, x)\n return ans \n```
| 6 | 0 |
['Python3']
| 0 |
maximum-difference-between-increasing-elements
|
Simple and Efficient In O(n) time
|
simple-and-efficient-in-on-time-by-coder-3jr6
|
\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nIn this we take difference with the minimum element found. We keep track of minimu
|
CoDer__01
|
NORMAL
|
2023-01-01T16:58:33.979479+00:00
|
2023-01-01T16:58:33.979519+00:00
| 1,098 | false |
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIn this we take difference with the minimum element found. We keep track of minimum element and maximum difference. And at each iteration we keep updating. And difference can be negative if the first element is largest so in that case we return -1.<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:**O(n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maximumDifference(int[] arr) {\n int arr_size=arr.length;\n int max_diff = arr[1] - arr[0];\n\t\tint min_element = arr[0];\n\t\tint i;\n\t\tfor (i = 1; i < arr_size; i++)\n\t\t{\n\t\t\tif (arr[i] - min_element > max_diff)\n\t\t\t\tmax_diff = arr[i] - min_element;\n\t\t\tif (arr[i] < min_element)\n\t\t\t\tmin_element = arr[i];\n\t\t}\n\t\tif (max_diff>0)\n return max_diff; \n else\n return -1;\n }\n}\n```
| 5 | 0 |
['Java']
| 2 |
maximum-difference-between-increasing-elements
|
Java Solution in O(n) time complexity
|
java-solution-in-on-time-complexity-by-a-009a
|
\nclass Solution {\n public int maximumDifference(int[] nums) {\n if(nums.length < 2)\n return -1;\n int result = Integer.MIN_VALUE;
|
akshatmathur23
|
NORMAL
|
2022-06-23T19:52:52.426929+00:00
|
2022-06-23T19:52:52.426969+00:00
| 1,036 | false |
```\nclass Solution {\n public int maximumDifference(int[] nums) {\n if(nums.length < 2)\n return -1;\n int result = Integer.MIN_VALUE;\n int minValue = nums[0];\n for(int i = 1; i < nums.length; i++) {\n if(nums[i] > minValue)\n result = Math.max(result, nums[i] - minValue);\n minValue = Math.min(minValue, nums[i]);\n }\n return result == Integer.MIN_VALUE ? -1 : result; \n }\n}\n```\nTime Complexity: O(n)\nSpace Complexity: O(1)\n\nGuy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE.
| 5 | 0 |
['Java']
| 0 |
maximum-difference-between-increasing-elements
|
Best Solution|| Similar to Best time to buy & sell a stock|| 0 ms|| O(n) complexity
|
best-solution-similar-to-best-time-to-bu-zz2q
|
image.png\n\n\n## Intuition\nThe problem is to find the maximum difference between any two elements in an array nums such that the second element appears after
|
aanyasharma2408
|
NORMAL
|
2024-04-30T09:22:36.337719+00:00
|
2024-04-30T09:22:36.337743+00:00
| 465 | false |
image.png\n\n\n## Intuition\nThe problem is to find the maximum difference between any two elements in an array `nums` such that the second element appears after the first. This can be approached by iterating through the array and keeping track of the minimum element encountered so far (`current_element`) and the maximum difference (`max_difference`) found.\n\n## Approach\n1. Initialize `current_element` to be the first element of the array `nums` and `max_difference` to `0`.\n2. Iterate through the array `nums` starting from the second element.\n3. For each element `nums[i]`:\n - Update `current_element` to be the minimum of `current_element` and `nums[i]`.\n - Calculate the difference `nums[i] - current_element`.\n - Update `max_difference` to be the maximum of `max_difference` and the calculated difference.\n4. After iterating through the array, if `max_difference` is still `0`, return `-1` indicating that no valid difference was found. Otherwise, return `max_difference` as the maximum difference found.\n\n## Complexity\n- Time Complexity: The algorithm has a time complexity of \\(O(n)\\), where \\(n\\) is the number of elements in the `nums` array. This is because we perform a single pass through the array to update `current_element` and `max_difference`.\n- Space Complexity: The algorithm has a space complexity of \\(O(1)\\) since we only use a constant amount of extra space for the `current_element` and `max_difference` variables, regardless of the size of the input array `nums`.\n\n```java\nclass Solution {\n public int maximumDifference(int[] nums) {\n int current_element = nums[0];\n int max_difference = 0;\n \n for (int i = 0; i < nums.length; i++) {\n if (nums[i] < current_element) {\n current_element = nums[i];\n }\n if (nums[i] - current_element > max_difference) {\n max_difference = nums[i] - current_element;\n }\n }\n \n if (max_difference == 0) {\n return -1; // Return -1 if no valid difference was found\n } else {\n return max_difference; // Return the maximum difference found\n }\n }\n}\n```\n\nThis solution efficiently computes the maximum difference between any two elements in the array `nums` based on the defined constraints and returns the result accordingly. The algorithm ensures optimal time and space complexity by utilizing a single pass through the array with constant space usage.
| 4 | 0 |
['Array', 'Math', 'Java']
| 0 |
maximum-difference-between-increasing-elements
|
C++ | 0 ms | Beats 100% | O(n) | Step By Step Explained 🚀
|
c-0-ms-beats-100-on-step-by-step-explain-tg78
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe algorithm uses two pointers, or positions, in the array to compare elements effecti
|
DJwhoCODES_5
|
NORMAL
|
2024-03-31T18:27:15.559783+00:00
|
2024-03-31T18:27:15.559815+00:00
| 367 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe algorithm uses two pointers, or positions, in the array to compare elements effectively. We decided to use two pointers because it helps us easily check each pair of adjacent elements in the array. This approach simplifies the process of finding the maximum difference between two elements by systematically examining each possible pair.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialization:\nn = nums.size(): Get the size of the input vector nums.\nCheck if the size of the array is less than 2. If so, it means there are not enough elements in the array to find a difference, so return -1.\n2. Variables Initialization:\nmaxDiff = -1: Initialize the variable maxDiff to store the maximum difference between two elements.\nleft = 0, right = 1: Initialize two pointers left and right pointing to the first and second elements of the array, respectively.\n3. Iterating through the Array:\n- Start a while loop iterating over the array elements starting from the second element (right = 1) until reaching the end of the array.\n- Inside the loop, compare the element at index left with the element at index right.\n- - If nums[left] < nums[right], it means the element at right is larger than the element at left. Calculate the difference (nums[right] - nums[left]) and update maxDiff if this difference is greater than the current maxDiff.\n- - Increment right to move to the next element.\n- - If nums[left] >= nums[right], it means the element at right is not greater than the element at left, so update left to right and move right to the next element.\n- - This is done, as values from left to right are increasing(that is why we were able to calculate the difference). So, any value between left and right will be greater than the value from nums[left] so left is updated to right.\n4. Return Result:\nOnce the loop completes, return the value of maxDiff, which represents the maximum difference found between two elements in the array where the larger element comes after the smaller element.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this algorithm is O(n), where n is the size of the input array nums, because it iterates through the array only once.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1), because the algorithm uses only a constant amount of extra space for storing variables irrespective of the size of the input array.\n\n# Code\n```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int n = nums.size();\n if (n < 2)\n return -1;\n\n int maxDiff = -1;\n int left = 0, right = 1;\n\n while (right < n) {\n if (nums[left] < nums[right]) {\n maxDiff = max(maxDiff, nums[right] - nums[left]);\n right++;\n } else {\n left = right;\n right++;\n }\n }\n\n return maxDiff;\n }\n};\n```
| 4 | 0 |
['Array', 'C++']
| 0 |
maximum-difference-between-increasing-elements
|
Easyy
|
easyy-by-arunvinod9497-3usg
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
arunvinod9497
|
NORMAL
|
2023-11-16T04:32:38.098345+00:00
|
2023-11-16T04:32:38.098369+00:00
| 371 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maximumDifference = function(nums) {\n\n let num=0;\n for(let i=0; i<nums.length;i++){\n for(let j= i+1; j<nums.length;j++){\n if(nums[j]>nums[i]){\n diff = nums[j]- nums[i];\n if(diff>num){\n num = diff;\n }\n }\n }\n }\n return num? num : -1;\n};\n```
| 4 | 0 |
['JavaScript']
| 1 |
maximum-difference-between-increasing-elements
|
🏆🔥✅O(N) Solution🏆🔥✅
|
on-solution-by-manohar_001-2un3
|
\uD83D\uDE09Don\'t just watch & move away, also give an Upvote.\uD83D\uDE09\n\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n)
|
Manohar_001
|
NORMAL
|
2023-10-01T11:33:58.056797+00:00
|
2023-10-01T11:33:58.056828+00:00
| 370 | false |
# \uD83D\uDE09Don\'t just watch & move away, also give an Upvote.\uD83D\uDE09\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int ans = 0;\n int minEle = nums[0];\n\n for(auto i=1; i<size(nums); i++)\n {\n minEle = min(minEle, nums[i]);\n ans = max(ans, nums[i]-minEle);\n }\n\n<!-- \u2705Well before returning answer don\'t forget to UPVOTE.\u2705 -->\n return ans == 0 ? -1:ans;\n }\n};\n```\n\n
| 4 | 0 |
['C', 'Python', 'C++', 'Java', 'JavaScript']
| 1 |
maximum-difference-between-increasing-elements
|
JavaScript O(n) solution (Runtime: 58 ms, faster than 98.91% submissions)
|
javascript-on-solution-runtime-58-ms-fas-4aw0
|
\nvar maximumDifference = function (nums) {\n let max = 0\n let minNum = nums[0]\n for (let i = 1; i < nums.length; i++) {\n let guess = nums[i]
|
norbekov
|
NORMAL
|
2022-07-26T13:27:55.585694+00:00
|
2022-07-26T13:31:26.657287+00:00
| 386 | false |
```\nvar maximumDifference = function (nums) {\n let max = 0\n let minNum = nums[0]\n for (let i = 1; i < nums.length; i++) {\n let guess = nums[i] - minNum\n if (guess > max) {\n max = guess\n }\n if (minNum > nums[i]) {\n minNum = nums[i]\n }\n }\n return max || -1\n};\n```
| 4 | 0 |
['JavaScript']
| 1 |
maximum-difference-between-increasing-elements
|
C++ Very Simple Approach || O(N) time || single iteration
|
c-very-simple-approach-on-time-single-it-q78x
|
\t\tint ans = 0,mini = nums[0],diff =0;\n for(int i=1;i<nums.size(); i++)\n {\n int a = nums[i];\n mini = min(a,mini);\n
|
anilsuthar
|
NORMAL
|
2022-07-20T10:08:00.838649+00:00
|
2022-07-20T10:08:00.838695+00:00
| 696 | false |
\t\tint ans = 0,mini = nums[0],diff =0;\n for(int i=1;i<nums.size(); i++)\n {\n int a = nums[i];\n mini = min(a,mini);\n diff = a-mini;\n ans = max(ans,diff);\n }\n if(ans<=0)return -1;\n return ans;\n\t\t\n\t\t\n\t\t\n****upvote if you find it helpfull****
| 4 | 0 |
['Array', 'C']
| 1 |
maximum-difference-between-increasing-elements
|
Java Simple Solution || 100% O(n)
|
java-simple-solution-100-on-by-shubhamkh-h2cq
|
\nclass Solution {\n public int maximumDifference(int[] nums) {\n int min=nums[0];\n int ans=-1;\n for(int i:nums){\n if(i<mi
|
shubhamkhatri474
|
NORMAL
|
2022-04-10T11:31:22.542052+00:00
|
2022-04-10T11:31:22.542096+00:00
| 381 | false |
```\nclass Solution {\n public int maximumDifference(int[] nums) {\n int min=nums[0];\n int ans=-1;\n for(int i:nums){\n if(i<min)\n min=i;\n if(i>min)\n ans=Math.max(ans,i-min);\n }\n return ans;\n }\n}\n```\n\n**Please UpVote!!**
| 4 | 0 |
['Java']
| 0 |
maximum-difference-between-increasing-elements
|
2016. Maximum Difference Between Increasing Elements
|
2016-maximum-difference-between-increasi-o5gi
|
int ans=0;\n int min=nums[0];\n for(int i=1;inums[i])\n min=nums[i];\n if(ans<(nums[i]-min))\n ans=nums[i
|
suyash_23
|
NORMAL
|
2022-01-20T06:59:49.566064+00:00
|
2022-01-21T17:43:46.372124+00:00
| 567 | false |
int ans=0;\n int min=nums[0];\n for(int i=1;i<nums.size();i++)\n {\n if(min>nums[i])\n min=nums[i];\n if(ans<(nums[i]-min))\n ans=nums[i]-min;\n }\n if(ans==0)\n return -1;\n return ans;
| 4 | 0 |
['Array', 'C']
| 0 |
maximum-difference-between-increasing-elements
|
Python3 || easy to understand || O(n)
|
python3-easy-to-understand-on-by-anilcho-le93
|
\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n mn,mx=float(\'inf\'),-1\n for i in range(len(nums)):\n mn
|
Anilchouhan181
|
NORMAL
|
2022-01-18T06:15:56.226251+00:00
|
2022-01-18T06:15:56.226290+00:00
| 697 | false |
```\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n mn,mx=float(\'inf\'),-1\n for i in range(len(nums)):\n mn=min(mn,nums[i])\n mx=max(mx,nums[i]-mn)\n if mx==0: return -1\n return mx\n```
| 4 | 0 |
['Python3']
| 3 |
maximum-difference-between-increasing-elements
|
c++(0ms 100%) greedy
|
c0ms-100-greedy-by-zx007pi-o4vr
|
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Maximum Difference Between Increasing Elements.\nMemory Usage: 8.3 MB, less than 42.76% of C++
|
zx007pi
|
NORMAL
|
2021-10-03T07:42:54.141833+00:00
|
2021-10-03T07:43:23.016353+00:00
| 645 | false |
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Maximum Difference Between Increasing Elements.\nMemory Usage: 8.3 MB, less than 42.76% of C++ online submissions for Maximum Difference Between Increasing Elements.\n```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int mini = nums[0], ans = -1;\n \n for(int i = 0; i != nums.size(); i++)\n if(nums[i] > mini) ans = max(ans, nums[i] - mini);\n else mini = min(nums[i], mini);\n \n return ans;\n }\n};\n```
| 4 | 0 |
['C', 'C++']
| 0 |
maximum-difference-between-increasing-elements
|
[Python3] Easiest O(n), O(1) space
|
python3-easiest-on-o1-space-by-shaad94-bh83
|
\n def maximumDifference(self, nums: List[int]) -> int:\n minimal = nums[0]\n\t\t# assign result as -1\n res = -1\n for n in nums[1:]:\n
|
shaad94
|
NORMAL
|
2021-09-26T07:41:13.522562+00:00
|
2021-09-26T07:44:06.639067+00:00
| 414 | false |
```\n def maximumDifference(self, nums: List[int]) -> int:\n minimal = nums[0]\n\t\t# assign result as -1\n res = -1\n for n in nums[1:]:\n\t\t # if current number is less than our minimal assign it to minimal\n if n <= minimal:\n minimal = n\n else:\n\t\t\t # if current number was not minimal check if difference would be bigger than we have\n res = max(res, n-minimal)\n return res\n```
| 4 | 0 |
[]
| 0 |
maximum-difference-between-increasing-elements
|
C++ || PREFIX SUM || EASY SOLUTION
|
c-prefix-sum-easy-solution-by-vineet_rao-em7c
|
\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int n=nums.size();\n int ans=INT_MIN;\n vector<int> right(n);
|
VineetKumar2023
|
NORMAL
|
2021-09-26T04:02:38.219140+00:00
|
2021-09-26T04:02:38.219168+00:00
| 299 | false |
```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int n=nums.size();\n int ans=INT_MIN;\n vector<int> right(n);\n right[n-1]=nums[n-1];\n for(int i=n-2;i>=0;i--)\n right[i]=max(right[i+1],nums[i]);\n for(int i=0;i<n-1;i++)\n {\n int x=right[i+1]-nums[i];\n if(x>0)\n {\n ans=max(ans,x);\n }\n }\n if(ans==INT_MIN)\n return -1;\n return ans;\n }\n};\n```
| 4 | 0 |
['C', 'Prefix Sum']
| 0 |
maximum-difference-between-increasing-elements
|
Simple python single pass solution
|
simple-python-single-pass-solution-by-sh-nz24
|
IntuitionWe need to track the smallest element and maxDifferenceApproachTravese throught the array and keep track of minimumElement and maximum difference.Compl
|
shubhagarwal539
|
NORMAL
|
2024-08-17T08:10:10.840099+00:00
|
2025-02-12T15:13:12.585451+00:00
| 214 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We need to track the smallest element and maxDifference
# Approach
<!-- Describe your approach to solving the problem. -->
Travese throught the array and keep track of minimumElement and maximum difference.
# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
# Initialize the minimum value as the first element of the array
minVal = nums[0]
# Initialize the maximum difference to -1 (default value if no valid difference is found)
maxDiff = -1
# Iterate through the list to find the maximum difference
for num in nums:
if num > minVal:
# Calculate the difference between the current number and the minimum value seen so far
diff = num - minVal
# Update maxDiff if the new difference is larger
maxDiff = max(maxDiff, diff)
else:
# Update minVal if a smaller number is encountered
minVal = num
# Return the maximum difference found (or -1 if no valid difference exists)
return maxDiff
```
| 3 | 0 |
['Python3']
| 1 |
maximum-difference-between-increasing-elements
|
0ms | Beats 100% | Tricky
|
0ms-beats-100-tricky-by-orewa_abhi-jwe3
|
Explanation\nIn the code\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n int maximumDifference(ve
|
Orewa_Abhi
|
NORMAL
|
2024-02-21T05:07:50.533352+00:00
|
2024-02-21T05:07:50.533390+00:00
| 289 | false |
# Explanation\nIn the code\n# Complexity\n- Time complexity:\n$$O(n)$$\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n // store the minimum value while traversing\n int mn = INT_MAX;\n // for default the answer is -1, incase of descending order\n int ans = -1;\n for(int i : nums)\n {\n // if we find any element lesser than mn, change mn\n if(mn > i)\n {\n mn = i;\n }\n // if the element is greater, make sure ith and jth index arent same\n else\n {\n if(mn != i)\n ans = max(ans, i-mn);\n }\n }\n return ans;\n \n }\n};\n```
| 3 | 0 |
['C++']
| 0 |
maximum-difference-between-increasing-elements
|
Maximum Difference Between Increasing Elements Solution in C++
|
maximum-difference-between-increasing-el-b4iu
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
The_Kunal_Singh
|
NORMAL
|
2023-05-01T04:36:21.164367+00:00
|
2023-05-01T04:36:21.164401+00:00
| 767 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int i=0, j, max=-1;\n for(j=1 ; j<nums.size() ; j++)\n {\n if(nums[i]<nums[j] && (nums[j]-nums[i])>max)\n {\n max = nums[j]-nums[i];\n }\n else if(nums[i]>=nums[j])\n {\n i = j;\n }\n }\n return max;\n }\n};\n```\n\n
| 3 | 0 |
['C++']
| 0 |
maximum-difference-between-increasing-elements
|
Greedy approch solution -->c++
|
greedy-approch-solution-c-by-sharma_hars-g6gi
|
class Solution {\npublic:\n int maximumDifference(vector& nums) \n {\n int minidx=INT_MAX;\n int ans=INT_MIN;\n for(int i=0;i<nums.si
|
sharma_harsh_glb
|
NORMAL
|
2022-09-27T06:37:51.128387+00:00
|
2022-09-27T06:37:51.128426+00:00
| 874 | false |
class Solution {\npublic:\n int maximumDifference(vector<int>& nums) \n {\n int minidx=INT_MAX;\n int ans=INT_MIN;\n for(int i=0;i<nums.size();i++)\n {\n minidx=min(nums[i],minidx);\n ans=max(ans,nums[i]-minidx);\n }\n if(ans==0)\n return -1;\n return ans;\n }\n\t//it is similiar to https://leetcode.com/problems/best-time-to-buy-and-sell-stock/?envType=study-plan&id=level-1//\n};
| 3 | 0 |
[]
| 0 |
maximum-difference-between-increasing-elements
|
100% Faster || Easy explanation
|
100-faster-easy-explanation-by-pratiktar-i7m4
|
Runtime: 0 ms, faster than 100.00% of Java online submissions\nMemory Usage: 41.4 MB, less than 96.55% of Java online submissions\n\n\nHere we are travesing thr
|
pratiktarale258
|
NORMAL
|
2022-09-05T09:40:11.403868+00:00
|
2022-09-05T09:40:11.403918+00:00
| 1,104 | false |
Runtime: 0 ms, faster than 100.00% of Java online submissions\nMemory Usage: 41.4 MB, less than 96.55% of Java online submissions\n\n\nHere we are travesing through array only once,\nwhile doing so we are performing 2 operations,\n1st:- finding minimum in an array,\n2nd:- finding max value of (current value-minimum value we found till now)\n\nif statement in code ensures that we wont subtract current number when it is being stored as min.\n\n\n\n public int maximumDifference(int[] nums) {\n int minn=nums[0];\n int maxn=-1;\n for(int i=0;i<nums.length;i++){\n \n if(minn>=nums[i]) //1st Part\n minn=nums[i];\n else {if(maxn<nums[i]-minn) //2nd Part\n maxn=nums[i]-minn;\n }\n }return maxn;\n }\n\n\n\nsame code can also be written as shown below using Math.max and Math.min functions.\n\n\n public int maximumDifference(int[] nums) {\n int minn=nums[0];\n int maxn=-1;\n for(int i=0;i<nums.length;i++){\n \n\t\t\tminn=Math.min(minn,nums[i]);\n if(minn<nums[i])\n maxn=Math.max(maxn,nums[i]-minn);\n \n\t\t\t}return maxn;\n }\n
| 3 | 0 |
['Java']
| 2 |
maximum-difference-between-increasing-elements
|
Java: short, easy to read, faster than 100%
|
java-short-easy-to-read-faster-than-100-v3lwc
|
\npublic int maximumDifference(int[] nums) {\n int min = Integer.MAX_VALUE;\n int maxGain = 0;\n for (int num:nums){\n if (n
|
gneginskiy
|
NORMAL
|
2022-07-20T02:49:19.528742+00:00
|
2022-07-20T02:50:11.653351+00:00
| 141 | false |
```\npublic int maximumDifference(int[] nums) {\n int min = Integer.MAX_VALUE;\n int maxGain = 0;\n for (int num:nums){\n if (num<min) min=num;\n else if(maxGain<num-min) maxGain=num-min;\n }\n return maxGain==0?-1:maxGain;\n}\n```
| 3 | 0 |
[]
| 0 |
maximum-difference-between-increasing-elements
|
Brother of Best Time to Buy and Sell Stocks
|
brother-of-best-time-to-buy-and-sell-sto-ynj0
|
Intuition and Approach:-\n\nThis is exactly the Best time to buy and sell stocks problem. Here\'s the solution to that problem- https://leetcode.com/problems/be
|
Predator_2K40
|
NORMAL
|
2022-06-12T07:08:54.094530+00:00
|
2022-06-12T07:09:31.644066+00:00
| 281 | false |
**Intuition and Approach:-**\n\nThis is exactly the ```Best time to buy and sell stocks``` problem. Here\'s the solution to that problem- https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/2140907/my-concise-java-on-solution\nHere, we only have to initiate max as -1, in case of a decreasing array.\n\n**Code:-**\n\n```\n public int maximumDifference(int[] nums) \n {\n int max=-1,lastindex=0;\n for (int i = 1; i < nums.length; i++)\n {\n if (nums[i]>nums[lastindex])\n max=Math.max(max,nums[i]-nums[lastindex]);\n else\n lastindex=i;\n }\n return max;\n }\n```\t
| 3 | 0 |
['Array', 'Java']
| 0 |
maximum-difference-between-increasing-elements
|
Simple python solution
|
simple-python-solution-by-trpaslik-l69z
|
Here is what I did:\n\npython\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n curmin = nums[0]\n diff = 0\n fo
|
trpaslik
|
NORMAL
|
2022-06-06T14:45:19.270850+00:00
|
2022-06-06T14:45:19.270890+00:00
| 533 | false |
Here is what I did:\n\n```python\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n curmin = nums[0]\n diff = 0\n for num in nums:\n diff = max(diff, num - curmin)\n curmin = min(curmin, num)\n return diff or -1\n```\n
| 3 | 0 |
['Python']
| 0 |
maximum-difference-between-increasing-elements
|
Python 🐍 easy, explained with comments || O(n) Time O(1) space || Beats 91%
|
python-easy-explained-with-comments-on-t-d0lx
|
The brute force solution would be iterating through the array and assuming current element is the minimum and finding the difference between the max element tow
|
dc_devesh7
|
NORMAL
|
2022-05-24T16:13:26.924477+00:00
|
2022-05-24T16:13:26.924524+00:00
| 711 | false |
The brute force solution would be iterating through the array and assuming current element is the minimum and finding the difference between the max element towards right the side and current element and then updating the max_difference accordingly. \nTo optimize this approach, I stored the current minimum in a variable and iterated through every element assuming it is the local maxima. The time complexity is therefore reduced to O(n) as each element is iterated only once.\n\n```\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n curr_min = nums[0]\n ans = 0\n \n for i in nums:\n if i < curr_min:\n curr_min = i\n \n ans = max(ans, i-curr_min)\n \n return -1 if ans == 0 else ans \n```
| 3 | 0 |
['Array', 'Dynamic Programming', 'Python', 'Python3']
| 0 |
maximum-difference-between-increasing-elements
|
2 Approaches to solve the problem- Using stack and general method
|
2-approaches-to-solve-the-problem-using-oo8po
|
By Using stack \n class Solution {\npublic:\n int maximumDifference(vector& nums) {\n int ans = -1;\n stack st;\n st.push(nums[0]);\n
|
priyesh_raj_singh
|
NORMAL
|
2022-03-12T13:18:33.835763+00:00
|
2022-03-12T13:21:29.570334+00:00
| 114 | false |
1. By Using stack \n class Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int ans = -1;\n stack<int> st;\n st.push(nums[0]);\n int diff = 0;\n for(int i = 1 ; i<nums.size() ; i++){\n if(nums[i]>st.top()){\n diff = nums[i]-st.top();\n ans = max(ans , diff);\n }\n else{\n st.pop();\n st.push(nums[i]);\n }\n }\n return ans; \n }\n};\n\n2. Generalize approach - by taking first element of nums as the minimum and proceed accordingly-\n\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n \n int mn=nums[0];\n int ans=-1;\n \n for(int i=1;i<nums.size();i++){\n if(nums[i]<mn)\n mn=nums[i];\n ans=max(ans,nums[i]-mn);\n }\n if(ans==0)\n ans=-1;\n return ans;\n }\n};\n
| 3 | 0 |
[]
| 0 |
maximum-difference-between-increasing-elements
|
Python3 solution | O(n) faster than 99%
|
python3-solution-on-faster-than-99-by-fl-ouo6
|
\'\'\'\n\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n my_max = -1\n min_here = math.inf # the minimum element unti
|
FlorinnC1
|
NORMAL
|
2021-09-28T20:43:48.598886+00:00
|
2021-09-28T20:43:48.598927+00:00
| 508 | false |
\'\'\'\n```\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n my_max = -1\n min_here = math.inf # the minimum element until i-th position\n for i in range(len(nums)):\n if min_here > nums[i]:\n min_here = nums[i]\n dif = nums[i] - min_here \n if my_max < dif and dif != 0: # the difference mustn\'t be 0 because nums[i] < nums[j] so they can\'t be equals\n my_max = dif\n return my_max\n```\nIf you like it, please upvote!^^\n\'\'\'
| 3 | 1 |
['Python', 'Python3']
| 0 |
maximum-difference-between-increasing-elements
|
C++ || Peak Valley || Explanation
|
c-peak-valley-explanation-by-aayushme-o64p
|
\nPeak Valley Concept\nEg [7,1,5,4]\n\n \n7\n \\ 5\n \\ / \\\n 1 4\n\n \nimin keep track ofvalley and imax keep track of difference of
|
aayushme
|
NORMAL
|
2021-09-26T04:02:00.000231+00:00
|
2021-09-26T04:03:41.028198+00:00
| 344 | false |
\n**Peak Valley Concept**\nEg `[7,1,5,4]`\n\n ```\n7\n \\ 5\n \\ / \\\n 1 4\n```\n \n`imin` keep track of` valley` and `imax` keep track of difference of `current_element-valley`\nThe answer will be difference of [5-1]\n\n```\nint maximumDifference(vector<int>& nums) {\n int imin=INT_MAX,imax=-1;\n for(int i=0;i<nums.size();i++){\n if(nums[i]<imin){\n imin=nums[i];\n }\n else{\n imax=max(imax,nums[i]-imin);\n }\n }\n return imax==0?-1:imax;\n}\n```
| 3 | 0 |
[]
| 1 |
maximum-difference-between-increasing-elements
|
Easiest Solution with simple approach beats 100%
|
easiest-solution-with-simple-approach-be-3bf4
|
Code
|
pawanps55
|
NORMAL
|
2025-01-08T08:17:11.374438+00:00
|
2025-01-08T08:17:11.374438+00:00
| 237 | false |
# Code
```cpp []
class Solution {
public:
int maximumDifference(vector<int>& nums) {
int minValue = nums[0];
int maxDifference = -1;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] > minValue) {
maxDifference = max(maxDifference, nums[i] - minValue);
} else {
minValue = nums[i];
}
}
return maxDifference;
}
};
```
| 2 | 0 |
['C++']
| 0 |
maximum-difference-between-increasing-elements
|
Solution in C
|
solution-in-c-by-akcyyix0sj-5a9f
|
Code
|
vickyy234
|
NORMAL
|
2025-01-05T06:51:36.293872+00:00
|
2025-01-05T06:51:36.293872+00:00
| 85 | false |
# Code
```c []
int maximumDifference(int* nums, int numsSize) {
int ans = -1;
int min = nums[0];
for (int i = 1; i < numsSize; i++) {
if (nums[i] < min)
min = nums[i];
else {
if (ans < nums[i] - min && min != nums[i])
ans = nums[i] - min;
}
}
return ans;
}
```
| 2 | 0 |
['C']
| 0 |
maximum-difference-between-increasing-elements
|
Simple C solution
|
simple-c-solution-by-tharunkumarsenthilk-eiyo
|
Intuition\nIdea is to find the smallest element and then find the element with which it has more difference.\n\n# Approach\n when the numsSize is below 2 , whic
|
TharunkumarSenthilkumar
|
NORMAL
|
2024-08-01T06:40:03.405953+00:00
|
2024-08-01T06:40:03.405973+00:00
| 47 | false |
# Intuition\nIdea is to find the smallest element and then find the element with which it has more difference.\n\n# Approach\n* when the `numsSize` is below 2 , which means there are no sufficient number of elements, so `return -1`\n* Initialise `minVal` to first digit `nums[0]`, `maxDiff` to `-1`\n* Iterate through the `nums` array. \n * if a number greater than `minVal` is found then find the difference between thise two numbers and store the value in `diff` variable.\n * if `diff` is greater than `maxDiff` then replace the value in `maxDiff` by `diff`\n * else if `nums[i]` is less tha n `minVal` then replace value in `minVal` with `nums[i]`\n* return `maxDiff`\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#include <limits.h>\n\nint maximumDifference(int* nums, int numsSize) {\n if (numsSize < 2) return -1;\n\n int minVal = nums[0];\n int maxDiff = -1;\n\n for (int i = 1; i < numsSize; i++) {\n if (nums[i] > minVal) {\n int diff = nums[i] - minVal;\n if (diff > maxDiff) {\n maxDiff = diff;\n }\n }\n if (nums[i] < minVal) {\n minVal = nums[i];\n }\n }\n\n return maxDiff;\n}\n\n```
| 2 | 0 |
['C']
| 0 |
maximum-difference-between-increasing-elements
|
Maximum Difference Between Increasing Elements || JAVA || Easiest Approach 🔥✅
|
maximum-difference-between-increasing-el-ef10
|
Code\n\nclass Solution {\n public int maximumDifference(int[] nums) {\n int max=0;\n for(int i=0;i<nums.length;i++)\n {\n for(int j=i+1;j<num
|
lohithmr494
|
NORMAL
|
2024-05-08T17:11:38.872479+00:00
|
2024-05-08T17:11:38.872503+00:00
| 106 | false |
# Code\n```\nclass Solution {\n public int maximumDifference(int[] nums) {\n int max=0;\n for(int i=0;i<nums.length;i++)\n {\n for(int j=i+1;j<nums.length;j++)\n {\n max=Math.max(max,nums[j]-nums[i]);\n }\n }\n return max>0?max:-1; \n }\n}\n```
| 2 | 0 |
['Array', 'Java']
| 0 |
maximum-difference-between-increasing-elements
|
Easiest Solutions in C++ / Python3 / Java / C# / Python / C / Go - beats 100%
|
easiest-solutions-in-c-python3-java-c-py-xmc4
|
Intuition\n\n\n\n\n\n Describe your first thoughts on how to solve this problem. \nC++ []\nclass Solution {\npublic:\n int maximumDifference(vector<int>& num
|
Edwards310
|
NORMAL
|
2024-04-05T01:21:04.428942+00:00
|
2024-04-05T01:21:04.428976+00:00
| 78 | false |
# Intuition\n\n\n\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n```C++ []\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int maxi = -1;\n for (int i = 0; i < nums.size() - 1; i++) {\n for (int j = i + 1; j < nums.size(); ++j)\n if (nums[i] < nums[j])\n maxi = max(maxi, nums[j] - nums[i]);\n }\n return maxi;\n }\n};\n```\n```python3 []\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n maxi = -1\n for i in range(len(nums) - 1):\n for j in range(i + 1, len(nums)):\n if nums[i] < nums[j]:\n maxi = max(maxi, nums[j] - nums[i])\n return maxi\n```\n```C# []\npublic class Solution {\n public int MaximumDifference(int[] nums) {\n int l = 0, r = 1, res = Int32.MinValue;\n while (r < nums.Length) {\n if (nums[r] > nums[l]) {\n res = Math.Max(res, nums[r] - nums[l]);\n r++;\n } else {\n l = r++;\n };\n }\n return (res == Int32.MinValue ? -1 : res);\n }\n}\n```\n```java []\nclass Solution {\n public int maximumDifference(int[] nums) {\n int l = 0, r = 1, res = Integer.MIN_VALUE;\n while (r < nums.length) {\n if (nums[r] > nums[l]) {\n res = Math.max(res, nums[r] - nums[l]);\n r++;\n } else {\n l = r++;\n };\n }\n return (res == Integer.MIN_VALUE ? -1 : res);\n }\n}\n```\n```python []\nclass Solution(object):\n def maximumDifference(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n buy = nums[0]\n profit = -1\n for i, num in enumerate(nums):\n if i == 0:\n continue\n current_profit = num - buy\n if buy < num:\n profit = max(current_profit, profit)\n else:\n buy = num\n return profit\n```\n```C []\nint maximumDifference(int* nums, int numsSize) {\n int l = 0, r = 1, res = INT_MIN;\n while (r < numsSize) {\n if (nums[r] > nums[l]) {\n res = fmax(res, nums[r] - nums[l]);\n r++;\n } else {\n l = r++;\n };\n }\n return (res == INT_MIN ? -1 : res);\n}\n```\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```\npublic class Solution {\n public int MaximumDifference(int[] nums) {\n int l = 0, r = 1, res = Int32.MinValue;\n while (r < nums.Length) {\n if (nums[r] > nums[l]) {\n res = Math.Max(res, nums[r] - nums[l]);\n r++;\n } else {\n l = r++;\n };\n }\n return (res == Int32.MinValue ? -1 : res);\n }\n}\n```\n# Thanks for viewing .. keep supporting me . Please upvote\n\n
| 2 | 0 |
['Array', 'C', 'Python', 'C++', 'Java', 'Python3', 'C#']
| 0 |
maximum-difference-between-increasing-elements
|
possible in this way also..
|
possible-in-this-way-also-by-sanal123-zfuv
|
Intuition\nThe function uses two nested loops to compare each element with all subsequent elements. \n\n# Approach\n Describe your approach to solving the probl
|
sanal123
|
NORMAL
|
2023-11-16T04:06:07.081240+00:00
|
2023-11-16T04:06:07.081270+00:00
| 320 | false |
# Intuition\nThe function uses two nested loops to compare each element with all subsequent elements. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(n^2)$$\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maximumDifference = function(nums) {\n let a=[];\n for(let i=0;i<nums.length;i++){\n for(let j=i+1;j<nums.length;j++){\n if(nums[i]<nums[j]){\n a.push(nums[j]-nums[i]);\n }\n }\n }\n \n let b=Math.max(...a);\n\n if(b==-Infinity){\n return -1;\n }else{\n return b;\n }\n \n\n};\n```
| 2 | 0 |
['JavaScript']
| 1 |
maximum-difference-between-increasing-elements
|
Python Elegant & Short | 1 pass
|
python-elegant-short-1-pass-by-kyrylo-kt-6oxy
|
\nfrom sys import maxsize\nfrom typing import List\n\n\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n curr_min = maxsize\n
|
Kyrylo-Ktl
|
NORMAL
|
2023-03-11T18:10:06.505558+00:00
|
2023-03-11T18:10:06.505614+00:00
| 1,184 | false |
```\nfrom sys import maxsize\nfrom typing import List\n\n\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n curr_min = maxsize\n max_diff = -1\n\n for num in nums:\n max_diff = max(max_diff, num - curr_min)\n curr_min = min(curr_min, num)\n\n return max_diff or -1\n\n```
| 2 | 0 |
['Python', 'Python3']
| 2 |
maximum-difference-between-increasing-elements
|
Sweet
|
sweet-by-nisaacdz-uewx
|
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co
|
nisaacdz
|
NORMAL
|
2023-01-28T11:52:28.846960+00:00
|
2023-01-28T11:52:28.847019+00:00
| 123 | false |
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Java []\nclass Solution {\n public int maximumDifference(int[] nums) {\n int diff = Integer.MIN_VALUE, num = nums[0];\n for(int i = 1; i < nums.length; i++) {\n if (nums[i] > num) {\n diff = Math.max(diff, nums[i] - num);\n }\n\n num = Math.min(num, nums[i]);\n }\n return diff == Integer.MIN_VALUE ? -1 : diff;\n }\n}\n```
| 2 | 0 |
['Java']
| 0 |
maximum-difference-between-increasing-elements
|
JAVA | | ThinkSimple (100% Efficiency)--;
|
java-thinksimple-100-efficiency-by-vasan-px9a
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
Vasanth_Kumar_29_19
|
NORMAL
|
2023-01-17T06:28:53.704419+00:00
|
2023-01-17T06:28:53.704492+00:00
| 513 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maximumDifference(int[] nums) {\n int max=0,min=nums[0];\n for(int i=1;i<nums.length;i++){\n if(nums[i]>min){\n int d=nums[i]-min;\n max=Math.max(d,max);\n }\n min=Math.min(min,nums[i]);\n }\n if(max>0)\n return max;\n return -1;\n }\n}\n```
| 2 | 0 |
['Java']
| 0 |
maximum-difference-between-increasing-elements
|
Easy Java Solution
|
easy-java-solution-by-fish12345-revz
|
\nclass Solution {\n public int maximumDifference(int[] nums) {\n int min = nums[0];\n int result = -1;\n for (int i = 1; i<nums.length;
|
fish12345
|
NORMAL
|
2022-12-04T23:42:02.848454+00:00
|
2022-12-04T23:42:02.848491+00:00
| 990 | false |
```\nclass Solution {\n public int maximumDifference(int[] nums) {\n int min = nums[0];\n int result = -1;\n for (int i = 1; i<nums.length; i++)\n {\n if (nums[i] > min)\n result = Math.max(result, nums[i] - min);\n else\n min = Math.min(min, nums[i]);\n }\n \n return result;\n }\n}\n```
| 2 | 0 |
['Java']
| 1 |
maximum-difference-between-increasing-elements
|
[JAVA] Easy to understand java solution.
|
java-easy-to-understand-java-solution-by-gw6r
|
Complexity\n- Time complexity O(n)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\n public int maximumDifference(int[] nums) {\n int res=0;
|
mihirbajpai
|
NORMAL
|
2022-11-27T10:14:26.447181+00:00
|
2022-11-27T10:14:26.447223+00:00
| 1,612 | false |
# Complexity\n- Time complexity $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n public int maximumDifference(int[] nums) {\n int res=0;\n int min=nums[0];\n for(int i=1; i<nums.length; i++){\n res=Math.max(res, nums[i]-min);\n min=Math.min(min, nums[i]);\n }\n if(res==0) return -1;\n return res;\n }\n}\n```
| 2 | 0 |
['Array', 'Java']
| 0 |
maximum-difference-between-increasing-elements
|
C++ solution easy to understand
|
c-solution-easy-to-understand-by-abdelna-jxmp
|
\n# Code\n\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int diff = -1;\n for(int i=0;i<nums.size();i++){\n
|
abdelnaby1
|
NORMAL
|
2022-10-15T16:19:34.841867+00:00
|
2022-10-15T16:19:34.841902+00:00
| 1,232 | false |
\n# Code\n```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int diff = -1;\n for(int i=0;i<nums.size();i++){\n int j = i + 1;\n while(j < nums.size() && nums[i] < nums[j]){\n if(nums[j] - nums[i] > diff){\n // cout<<diff<<" ";\n cout<<nums[j]-nums[i];\n diff = nums[j]-nums[i];\n }\n j++;\n }\n }\n return diff;\n }\n\n};\n```
| 2 | 0 |
['C++']
| 1 |
maximum-difference-between-increasing-elements
|
100% FASTER || EASY TO UNDERSTAND [JAVA CODE]
|
100-faster-easy-to-understand-java-code-7leen
|
\nclass Solution {\n public int maximumDifference(int[] nums) {\n int min = nums[0];\n int diff = -1;\n \n for(int i=1; i<nums.le
|
priyankan_23
|
NORMAL
|
2022-09-04T19:25:01.004555+00:00
|
2022-09-04T19:25:01.004578+00:00
| 473 | false |
```\nclass Solution {\n public int maximumDifference(int[] nums) {\n int min = nums[0];\n int diff = -1;\n \n for(int i=1; i<nums.length; i++){\n if(nums[i] > min){\n int d=nums[i]-min;\n diff = Math.max(diff, d);\n }else{\n min = nums[i];\n }\n }\n \n return diff;\n }\n}\n```
| 2 | 0 |
[]
| 0 |
maximum-difference-between-increasing-elements
|
JAVA - Simple and easy to understand || TC- O(n) || SC - O(1)
|
java-simple-and-easy-to-understand-tc-on-050o
|
Approach - According to the question we are required to find the maximum difference between the adjacent elements .The answer will be the maximum difference out
|
Kunal_pratap
|
NORMAL
|
2022-08-30T07:17:14.271051+00:00
|
2022-11-06T05:10:53.197446+00:00
| 243 | false |
**Approach** - According to the question we are required to find the maximum difference between the adjacent elements .The answer will be the maximum difference out of all differences calculated .\nNow it is very obvious to think that maximum difference can only be possible if we find the maximum element lying ahead of any element ,so we start from end.\nWe take a max variable and initialize it to last element and start the loop from second last position.\n\n**Our plan is to maintain a max value which will be the greatest among all elements that are to the right side of that element so that we don\'t need to traverse every time to find the max element and hence the maximum difference,we can directly subtract the max value from the element and get the difference.**\nAlso we store that difference in a diff variable initialized to zero. As we want to get the maximum difference we don\'t update it everytime when we find the difference , rather we do it only when we get a difference that is greater than previously calculated differences .\nIn this way we find the maximum difference using a single loop in **TC - O(N)** and **SC -O(1)**\n\n\n\n```\nCode block\n```\n\n public int maximumDifference(int[] arr) \n\t{\n int max=arr[arr.length-1] , diff=-1;\n for(int i=arr.length-2;i>=0;i--)\n {\n if(max>arr[i])\n diff=Math.max(diff,max-arr[i]);\n else\n max=arr[i];\n\t\t\t\t// update max if we find a element greater than it.\n }\n return diff;\n }\n\n\n\n**Please upvote if u find it helpful and worth reading**
| 2 | 0 |
['Java']
| 0 |
maximum-difference-between-increasing-elements
|
[Python3] Straightforward O(n) no extra space w comments
|
python3-straightforward-on-no-extra-spac-agfh
|
```py\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n output = -1\n low = 10**9 # Set because of question constraints
|
connorthecrowe
|
NORMAL
|
2022-08-29T21:02:26.952492+00:00
|
2022-08-29T21:02:26.952534+00:00
| 577 | false |
```py\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n output = -1\n low = 10**9 # Set because of question constraints\n \n for i in range(len(nums)):\n # If we come across a new lowest number, keep track of it\n low = min(low, nums[i])\n \n # If the current number is greater than our lowest - and if their difference is greater than\n # the largest distance seen yet, save this distance\n if nums[i] > low: output = max(output, nums[i] - low)\n return output
| 2 | 0 |
['Python', 'Python3']
| 0 |
maximum-difference-between-increasing-elements
|
C++| Easy-Explanation | O(N)
|
c-easy-explanation-on-by-modisanskar5-5adn
|
Logic\n\n- We will keep track of difference at each index(res) and the minimum value(min_Ele).\n\n- We will be updating the res with max difference and min_Ele
|
modisanskar5
|
NORMAL
|
2022-07-08T13:23:36.927499+00:00
|
2022-07-08T13:23:36.927606+00:00
| 481 | false |
## Logic\n\n- We will keep track of **difference at each index**(res) and the **minimum value**(min_Ele).\n\n- We will be updating the res with max difference and min_Ele with the smallest element.\n\n- The condition that *j>i* and *nums[j]>nums[i]* is satisfied by above two points.\n\n## Implementation\n```\nint maximumDifference(vector<int> &nums)\n{\n int res = nums[1] - nums[0];\n // Initializing the difference\n int min_Ele = nums[0];\n // Minimum Elemeng at each iteration\n for (int i = 1; i < nums.size(); i++)\n {\n res = max(res, nums[i] - min_Ele);\n // Updating the difference\n min_Ele = min(nums[i], min_Ele);\n // Updating the minimum element\n }\n return res <= 0 ? -1 : res;\n}\n```\n- TC - O(N)\n**Thank You!** for reading . Do upvote \uD83D\uDC4Dif you like the explanation if there is any scope of improvement do mention it in comments\uD83D\uDE01.
| 2 | 0 |
['Array', 'C', 'C++']
| 0 |
maximum-difference-between-increasing-elements
|
cpp soln
|
cpp-soln-by-sejalrai-kcfd
|
int maximumDifference(vector& nums) {\n vector v;\n for(int i=0;i<nums.size();i++)\n {\n for(int j=i+1;jnums[i])\n v.push_back(nu
|
sejalrai
|
NORMAL
|
2022-01-27T10:38:22.663962+00:00
|
2022-01-27T10:38:22.663989+00:00
| 255 | false |
int maximumDifference(vector<int>& nums) {\n vector<int> v;\n for(int i=0;i<nums.size();i++)\n {\n for(int j=i+1;j<nums.size();j++)\n {\n if(nums[j]>nums[i])\n v.push_back(nums[j]-nums[i]);\n }\n }\n sort(v.begin(),v.end());\n \n if(v.size()==0)\n return -1;\n else\n return v[v.size()-1];\n }\n};
| 2 | 0 |
['C++']
| 0 |
maximum-difference-between-increasing-elements
|
[C++] Clear understanding of Best time to buy and sell stocks
|
c-clear-understanding-of-best-time-to-bu-td71
|
\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int ans = 0;\n int prev = nums[0];\n for(int i=1;i<nums.size(
|
sanjana-302
|
NORMAL
|
2021-12-10T14:22:00.745142+00:00
|
2021-12-10T14:22:00.745170+00:00
| 140 | false |
```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int ans = 0;\n int prev = nums[0];\n for(int i=1;i<nums.size();i++){\n prev = min(prev,nums[i]);\n ans = max(ans,nums[i] - prev);\n }\n return ans==0?-1:ans;\n }\n};\n```\nThe problem statement is a classified explanation of Best Time Buy and Sell Stock.
| 2 | 0 |
['C']
| 1 |
maximum-difference-between-increasing-elements
|
JavaScript O(n) solution
|
javascript-on-solution-by-rangerua-8r0b
|
\nconst maximumDifference = nums => {\n let res = -1;\n let pointer1 = 0;\n let pointer2 = 1;\n \n while (pointer2 <= nums.length - 1) {\n
|
rangerua
|
NORMAL
|
2021-12-09T22:15:28.095612+00:00
|
2021-12-09T22:15:28.095660+00:00
| 328 | false |
```\nconst maximumDifference = nums => {\n let res = -1;\n let pointer1 = 0;\n let pointer2 = 1;\n \n while (pointer2 <= nums.length - 1) {\n if (nums[pointer1] < nums[pointer2]) {\n res = (nums[pointer2] - nums[pointer1]) > res \n ? nums[pointer2] - nums[pointer1] \n : res;\n } else {\n pointer1 = pointer2;\n }\n \n pointer2++;\n }\n \n return res;\n}\n```
| 2 | 0 |
['Two Pointers', 'JavaScript']
| 0 |
maximum-difference-between-increasing-elements
|
Java O(n) solution
|
java-on-solution-by-rangerua-zvuv
|
\npublic int maximumDifference(int[] nums) {\n int result = -1;\n int pointer1 = 0;\n int pointer2 = 1;\n\n while (pointer2 < nums.length) {\n
|
rangerua
|
NORMAL
|
2021-12-08T23:19:37.632644+00:00
|
2021-12-08T23:19:37.632681+00:00
| 200 | false |
```\npublic int maximumDifference(int[] nums) {\n int result = -1;\n int pointer1 = 0;\n int pointer2 = 1;\n\n while (pointer2 < nums.length) {\n int diff = nums[pointer2] - nums[pointer1];\n\n if (diff < 0) {\n pointer1 = pointer2;\n } else if (diff > 0 && diff > result) {\n result = diff;\n }\n\n pointer2++;\n }\n\n return result;\n}\n```
| 2 | 0 |
['Java']
| 0 |
maximum-difference-between-increasing-elements
|
CPP 0ms solution
|
cpp-0ms-solution-by-ashwinipush-axe4
|
\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int n = nums.size();\n vector<int> rightmax(n,0);\n rightmax[
|
ashwinipush
|
NORMAL
|
2021-11-21T20:32:38.320659+00:00
|
2021-11-21T20:32:38.320703+00:00
| 72 | false |
```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\n int n = nums.size();\n vector<int> rightmax(n,0);\n rightmax[n-1] = 0;int right = 0;\n for(int i = n-2; i>=0 ; i--)\n {\n rightmax[i] = max(nums[i+1], right);\n right = rightmax[i];\n }\n int ans = 0;\n for(int i = 0 ;i< n ;i++)\n {\n if(nums[i] < rightmax[i])\n ans = max(ans,abs(nums[i] - rightmax[i]));\n }\n if(ans == 0)\n return -1;\n return ans;\n }\n};\n```
| 2 | 0 |
[]
| 0 |
maximum-difference-between-increasing-elements
|
Java Solution - O(n)
|
java-solution-on-by-komsat-83dp
|
\npublic int maximumDifference(int[] nums) {\n int maxDiff = 0;\n int minVal = Integer.MAX_VALUE;\n \n for(int i = 0; i < nums.lengt
|
komsat
|
NORMAL
|
2021-10-03T08:19:28.055157+00:00
|
2021-10-03T08:19:28.055198+00:00
| 108 | false |
```\npublic int maximumDifference(int[] nums) {\n int maxDiff = 0;\n int minVal = Integer.MAX_VALUE;\n \n for(int i = 0; i < nums.length; i++) {\n minVal = Math.min(minVal, nums[i]);\n maxDiff = Math.max(maxDiff, nums[i]-minVal);\n }\n \n if(maxDiff == 0)\n return -1;\n \n return maxDiff;\n }\n```
| 2 | 0 |
[]
| 0 |
maximum-difference-between-increasing-elements
|
c++ simple solution || brute force and dp ;)
|
c-simple-solution-brute-force-and-dp-by-ilt28
|
1)BRUTE FORCE\n\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\nint ans=0;\nint count=0;\nfor(int i=0 ; i<nums.size() ; i++)\n{\n
|
mayuresh1377
|
NORMAL
|
2021-10-01T14:15:12.409559+00:00
|
2021-10-02T08:22:55.942436+00:00
| 146 | false |
1)BRUTE FORCE\n```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\nint ans=0;\nint count=0;\nfor(int i=0 ; i<nums.size() ; i++)\n{\n for(int j=i+1 ; j<nums.size() ; j++)\n {\n count=nums[j]-nums[i];\n ans=max(ans, count);\n }\n}\nreturn ans==0?-1:ans;\n }\n};\n```\n2)DYNAMIC PROGRAMMING\n```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& nums) {\nint ans=-1;\nint m=INT_MAX;\nfor(int i=0 ; i<nums.size() ; i++)\n{\n m=min(m , nums[i]);\n if(nums[i]>m) ans=max(ans , nums[i]-m);\n}\n return ans;\n }\n};\n```\n\nfound it helpful ? please upvote ;)
| 2 | 1 |
['Dynamic Programming', 'C']
| 0 |
maximum-difference-between-increasing-elements
|
[JAVA] Easy, Clean and Concise Solution - O(N) - 0ms - Faster than 100%
|
java-easy-clean-and-concise-solution-on-34cr8
|
\nclass Solution {\n public int maximumDifference(int[] nums) {\n int min = Integer.MAX_VALUE;\n int ans = -1;\n for(int i = 0; i < nums
|
Dyanjno123
|
NORMAL
|
2021-10-01T06:37:14.789012+00:00
|
2021-10-01T06:37:14.789056+00:00
| 221 | false |
```\nclass Solution {\n public int maximumDifference(int[] nums) {\n int min = Integer.MAX_VALUE;\n int ans = -1;\n for(int i = 0; i < nums.length; i++){\n if(nums[i] > min){\n if(nums[i] - min > ans)\n ans = nums[i] - min;\n }else\n min = nums[i];\n }\n return ans;\n }\n}\n```
| 2 | 0 |
['Java']
| 0 |
maximum-difference-between-increasing-elements
|
Rust solution
|
rust-solution-by-bigmih-ly2a
|
\nimpl Solution {\n pub fn maximum_difference(nums: Vec<i32>) -> i32 {\n let mut diff = -1;\n let (mut max, mut min) = (nums[0], nums[0]);\n
|
BigMih
|
NORMAL
|
2021-09-28T19:53:33.761786+00:00
|
2021-09-28T19:53:33.761816+00:00
| 94 | false |
```\nimpl Solution {\n pub fn maximum_difference(nums: Vec<i32>) -> i32 {\n let mut diff = -1;\n let (mut max, mut min) = (nums[0], nums[0]);\n for &val in nums[1..].iter() {\n if val < min {\n min = val;\n max = val;\n } else if val > max {\n max = val;\n diff = diff.max(max - min);\n }\n }\n diff\n }\n}\n```
| 2 | 0 |
['Rust']
| 1 |
maximum-difference-between-increasing-elements
|
Java O(n)
|
java-on-by-vikrant_pc-fo4q
|
\npublic int maximumDifference(int[] nums) {\n\tint result = -1, min = nums[0];\n\tfor(int i=1;i<nums.length;i++) {\n\t\tif(nums[i] != min) result = Math.max(re
|
vikrant_pc
|
NORMAL
|
2021-09-26T04:17:16.625067+00:00
|
2021-09-26T04:17:16.625119+00:00
| 210 | false |
```\npublic int maximumDifference(int[] nums) {\n\tint result = -1, min = nums[0];\n\tfor(int i=1;i<nums.length;i++) {\n\t\tif(nums[i] != min) result = Math.max(result, nums[i] - min);\n\t\tmin = Math.min(min, nums[i]);\n\t}\n\treturn result;\n}\n```
| 2 | 0 |
[]
| 1 |
maximum-difference-between-increasing-elements
|
C++| O(N^2)
|
c-on2-by-coder_shubham_24-o8z1
|
\nclass Solution {\npublic:\n int maximumDifference(vector<int>& a) {\n \n int i,j,ans=0,n=a.size(),f=0;\n \n for(i=0;i<n;i++){\n
|
Coder_Shubham_24
|
NORMAL
|
2021-09-26T04:03:19.342643+00:00
|
2021-09-26T04:03:19.342681+00:00
| 163 | false |
```\nclass Solution {\npublic:\n int maximumDifference(vector<int>& a) {\n \n int i,j,ans=0,n=a.size(),f=0;\n \n for(i=0;i<n;i++){\n for(j=i+1;j<n;j++){\n \n if(a[j]>a[i]){\n f++;\n ans = max(ans, a[j]-a[i]);\n }\n \n }\n }\n \n if(f>0)\n return ans;\n \n return -1;\n }\n};\n```
| 2 | 0 |
[]
| 0 |
maximum-difference-between-increasing-elements
|
Beats 100% || easy || 0ms solution...
|
beats-100-easy-0ms-solution-by-arun_geor-45b1
|
IntuitionThe problem requires finding the maximum difference between two elements in the list such that the larger element appears after the smaller element.
A
|
Arun_George_
|
NORMAL
|
2025-03-26T15:31:27.566209+00:00
|
2025-03-26T15:31:27.566209+00:00
| 196 | false |
# Intuition
The problem requires finding the maximum difference between two elements in the list such that the larger element appears after the smaller element.
A naive approach would be to check every pair, but we can optimize by keeping track of the minimum element encountered so far while iterating.

# Approach
- Initialize `max_diff` as `0` and `min_elem` as the first element of `nums`.
- Iterate through `nums`, updating `max_diff` as the maximum difference found so far.
- Also, update `min_elem` to keep track of the smallest element encountered so far.
- If `max_diff` remains `0`, return `-1` since no valid difference exists.
# Complexity
- **Time complexity:** $$O(n)$$
Since we only iterate through the list once, the time complexity is linear.
- **Space complexity:** $$O(1)$$
We only use a few extra variables, so the space complexity is constant.
# Code
```python []
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
max_diff = 0
min_elem = nums[0]
for i in nums:
max_diff = max(max_diff, i - min_elem)
min_elem = min(min_elem, i)
return max_diff if max_diff > 0 else -1
```
```c []
int maximumDifference(int nums[], int size) {
int max_diff = -1, min_elem = nums[0];
for (int i = 1; i < size; i++) {
if (nums[i] > min_elem) {
max_diff = (nums[i] - min_elem > max_diff) ? nums[i] - min_elem : max_diff;
}
if (nums[i] < min_elem) {
min_elem = nums[i];
}
}
return max_diff;
}
```
```C++ []
class Solution {
public:
int maximumDifference(vector<int>& nums) {
int max_diff = -1, min_elem = nums[0];
for (int i = 1; i < nums.size(); i++) {
if (nums[i] > min_elem) {
max_diff = max(max_diff, nums[i] - min_elem);
}
min_elem = min(min_elem, nums[i]);
}
return max_diff;
}
};
```
``` Java []
class Solution {
public int maximumDifference(int[] nums) {
int max_diff = -1, min_elem = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > min_elem) {
max_diff = Math.max(max_diff, nums[i] - min_elem);
}
min_elem = Math.min(min_elem, nums[i]);
}
return max_diff;
}
}
```
| 1 | 0 |
['Array', 'C', 'Python', 'C++', 'Java', 'Python3']
| 0 |
maximum-difference-between-increasing-elements
|
<<BEAT 100% SOLUTIONS>>
|
beat-100-solutions-by-dakshesh_vyas123-i6xl
|
PLEASE UPVOTE MECode
|
Dakshesh_vyas123
|
NORMAL
|
2025-03-22T07:08:40.672099+00:00
|
2025-03-22T07:08:40.672099+00:00
| 58 | false |
# PLEASE UPVOTE ME
# Code
```cpp []
class Solution {
public:
int maximumDifference(vector<int>& nums) {
int m=nums[0],ans=-1;
for(int i=1;i<nums.size();i++){
if(nums[i]>m) ans=max(ans,(nums[i]-m));
else m=nums[i];}
return ans;
}
};
```
| 1 | 0 |
['C++']
| 0 |
maximum-difference-between-increasing-elements
|
Bets 100% runtime and memory
|
bets-100-runtime-and-memory-by-govindsku-1oaf
|
Quote
Everything should be made as simple as possible, but not simpler.
Code
|
govindskumar619
|
NORMAL
|
2025-03-12T07:35:05.778325+00:00
|
2025-03-12T07:35:05.778325+00:00
| 27 | false |
> Quote
Everything should be made as simple as possible, but not simpler.
# Code
```golang []
func maximumDifference(nums []int) int {
out:= -1
for i:= 0 ; i< len(nums)-1; i++{
for j:= i+1 ;j< len(nums); j++{
if nums[j]-nums[i]>out && nums[j]-nums[i] != 0{
out=nums[j]-nums[i]
}
}
}
return out
}
```
| 1 | 0 |
['Go']
| 0 |
maximum-difference-between-increasing-elements
|
EASY SOLUTION IN JAVA
|
easy-solution-in-java-by-vikram_s_2004-w27t
|
IntuitionkceApproachIterate Over the Array:Complexity
Time complexity:
o(N)
Space complexity:
o(1)Code
|
VIKRAM_S_2004
|
NORMAL
|
2025-02-25T09:31:19.557659+00:00
|
2025-02-25T09:31:19.557659+00:00
| 226 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
kce
# Approach
<!-- Describe your approach to solving the problem. -->
Iterate Over the Array:
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
**o(N)**
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
**o(1)**
# Code
```java []
class Solution {
public int maximumDifference(int[] nums) {
int b = Integer.MAX_VALUE;
int maxDiff = -1;
for(int i = 0; i<nums.length; i++){
if(b < nums[i]){
int p = nums[i] - b;
maxDiff = Math.max(maxDiff, p);
}
else{
b = nums[i];
}
}
return maxDiff;
}
}
```
| 1 | 0 |
['Iterator', 'Java']
| 0 |
maximum-difference-between-increasing-elements
|
beat 100% runtime for swift solution
|
beat-100-runtime-for-swift-solution-by-c-yxte
|
IntuitionWe are given an array of integers, and we need to find the maximum difference between two elements such that the larger element comes after the smaller
|
ChocoletEY
|
NORMAL
|
2025-02-22T00:19:57.714584+00:00
|
2025-02-22T00:19:57.714584+00:00
| 12 | false |
# Intuition
We are given an array of integers, and we need to find the maximum difference between two elements such that the larger element comes after the smaller element. The key idea is to track the minimum value encountered so far as we iterate through the array, and for each element, calculate the difference with this minimum value. We then keep track of the maximum difference found.
# Approach
1. Initialize a variable to keep track of the minimum value encountered so far.
2. Initialize a variable to store the maximum difference found.
3. Iterate through the array. For each element:
- Update the minimum value if the current element is smaller.
- Calculate the difference between the current element and the minimum value.
- Update the maximum difference if the calculated difference is greater.
4. Return the maximum difference found. If no valid difference is found (i.e., array elements are non-increasing), return -1.
# Complexity
- Time complexity: O(n), where n is the number of elements in the array. We only iterate through the array once.
- Space complexity: O(1). We are using a constant amount of extra space.
# Code
```swift []
class Solution {
func maximumDifference(_ nums: [Int]) -> Int {
// Initialize the minimum value with the first element
var minVal = nums[0]
// Initialize the maximum difference with -1
var maxDiff = -1
// Iterate through the array starting from the second element
for i in 1..<nums.count {
// If the current element is greater than the minimum value,
// calculate the difference and update maxDiff if needed
if nums[i] > minVal {
maxDiff = max(maxDiff, nums[i] - minVal)
} else {
// Update the minimum value if the current element is smaller
minVal = nums[i]
}
}
// Return the maximum difference found or -1 if no valid difference
return maxDiff
}
}
```
| 1 | 0 |
['Swift']
| 0 |
maximum-difference-between-increasing-elements
|
Java Easy Solution
|
java-easy-solution-by-wojak202611-6up0
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
wojak202611
|
NORMAL
|
2025-02-09T19:17:59.281035+00:00
|
2025-02-09T19:17:59.281035+00:00
| 214 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int maximumDifference(int[] nums) {
int b = Integer.MAX_VALUE;
int maxDiff = -1;
for(int i = 0; i<nums.length; i++){
if(b < nums[i]){
int p = nums[i] - b;
maxDiff = Math.max(maxDiff, p);
}
else{
b = nums[i];
}
}
return maxDiff;
}
}
```
| 1 | 0 |
['Java']
| 0 |
maximum-difference-between-increasing-elements
|
Easy Java Solution beats 100%
|
easy-java-solution-beats-100-by-chandran-wzc5
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Chandranshu31
|
NORMAL
|
2025-02-08T06:22:55.207852+00:00
|
2025-02-08T06:22:55.207852+00:00
| 139 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)
# Code
```java []
class Solution {
public int maximumDifference(int[] nums) {
int a =Integer.MAX_VALUE; // a variable to track current. same question as buy and sell stock
int maxDiff=-1;
for(int i=0;i<nums.length;i++){
if(a<nums[i]){
int diff = nums[i]-a;
maxDiff= Math.max(diff,maxDiff);
}
else{
a=nums[i];
}
}
return maxDiff;
}
}
```
| 1 | 0 |
['Java']
| 0 |
maximum-difference-between-increasing-elements
|
4MS 🏆 || JAVA ☕
|
4ms-java-by-galani_jenis-fiws
|
Code
|
Galani_jenis
|
NORMAL
|
2025-01-23T04:47:23.325484+00:00
|
2025-01-23T04:47:23.325484+00:00
| 135 | false |
# Code
```java []
class Solution {
public int maximumDifference(int[] nums) {
int ans = -1;
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (ans > (nums[j] - nums[i])) {
continue;
} else {
if (nums[j] > nums[i]) {
ans = nums[j] - nums[i];
}
}
}
}
return ans;
}
}
```

| 1 | 0 |
['Java']
| 0 |
maximum-difference-between-increasing-elements
|
run time 0ms Beat 100%
|
run-time-0ms-beat-100-by-chandra158-z0kk
|
IntuitionApproachComplexity
Time complexity: O(n)
Space complexity: O(1)
Code
|
Chandra158
|
NORMAL
|
2025-01-21T12:43:01.371862+00:00
|
2025-01-21T12:43:01.371862+00:00
| 109 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: **O(n)**
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: **O(1)**
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int maximumDifference(vector<int>& nums) {
int n = nums.size();
int min_element = nums[0];
int max_diff = -1; // Initialize to -1 to indicate no valid pair found
for (int i = 1; i < n; i++) {
if (nums[i] > min_element) {
max_diff = max(max_diff, nums[i] - min_element);
} else {
min_element = nums[i];
}
}
return max_diff;
}
};
```
| 1 | 0 |
['C++']
| 0 |
maximum-difference-between-increasing-elements
|
Simple C program solution
|
simple-c-program-solution-by-aswath_1192-hern
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Aswath_1192
|
NORMAL
|
2025-01-01T16:39:07.735214+00:00
|
2025-01-01T16:39:07.735214+00:00
| 47 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```c []
int maximumDifference(int* nums, int numsSize) {
int maxd=-1,minval;
for(int i=0;i<numsSize-1;i++){
for(int j=i+1;j<numsSize;j++){
if(nums[i]<nums[j]){
minval=nums[j]-nums[i];
if(minval>maxd){
maxd=minval;
}}
}}
return maxd;
}
```
| 1 | 0 |
['C']
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.