2016. Maximum Difference Between Increasing Elements LeetCode Solution
In this guide, you will get 2016. Maximum Difference Between Increasing Elements LeetCode Solution with the best time and space complexity. The solution to Maximum Difference Between Increasing Elements problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Maximum Difference Between Increasing Elements solution in C++
- Maximum Difference Between Increasing Elements solution in Java
- Maximum Difference Between Increasing Elements solution in Python
- Additional Resources

Problem Statement of Maximum Difference Between Increasing Elements
Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] – nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].
Return the maximum difference. If no such i and j exists, return -1.
Example 1:
Input: nums = [7,1,5,4]
Output: 4
Explanation:
The maximum difference occurs with i = 1 and j = 2, nums[j] – nums[i] = 5 – 1 = 4.
Note that with i = 1 and j = 0, the difference nums[j] – nums[i] = 7 – 1 = 6, but i > j, so it is not valid.
Example 2:
Input: nums = [9,4,3,2]
Output: -1
Explanation:
There is no i and j such that i < j and nums[i] < nums[j].
Example 3:
Input: nums = [1,5,2,10]
Output: 9
Explanation:
The maximum difference occurs with i = 0 and j = 3, nums[j] – nums[i] = 10 – 1 = 9.
Constraints:
n == nums.length
2 <= n <= 1000
1 <= nums[i] <= 109
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
2016. Maximum Difference Between Increasing Elements LeetCode Solution in C++
class Solution {
public:
int maximumDifference(vector<int>& nums) {
int ans = -1;
int mn = nums[0];
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] > mn)
ans = max(ans, nums[i] - mn);
mn = min(mn, nums[i]);
}
return ans;
}
};
/* code provided by PROGIEZ */
2016. Maximum Difference Between Increasing Elements LeetCode Solution in Java
class Solution {
public int maximumDifference(int[] nums) {
int ans = -1;
int mn = nums[0];
for (int i = 1; i < nums.length; ++i) {
if (nums[i] > mn)
ans = Math.max(ans, nums[i] - mn);
mn = Math.min(mn, nums[i]);
}
return ans;
}
}
// code provided by PROGIEZ
2016. Maximum Difference Between Increasing Elements LeetCode Solution in Python
class Solution:
def maximumDifference(self, nums: list[int]) -> int:
ans = -1
mn = nums[0]
for i in range(len(nums)):
if nums[i] > mn:
ans = max(ans, nums[i] - mn)
mn = min(mn, nums[i])
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.