Leetcode 2016. Maximum Difference Between Increasing Elements
Given a 0-indexed integer array nums of size n, you need to 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.
Input: nums = [7,1,5,4]
Output: 4
Explanation:
The maximum difference occurs with i = 1 and j = 2 (nums[2] - nums[1] = 5 - 1 = 4).
nums?
n will be within the range from 1 to 10^3.nums?
A straightforward approach to solve this problem is to use a single pass scan while keeping track of the minimum element seen so far. At every position j, the difference nums[j] - min_value is computed, and the maximum difference is kept track of. Here is a more detailed algorithm:
min_value with the first element of the array.max_diff as -1 (since we need to return -1 if no such i and j exists).min_value.max_diff if the difference is larger than the current max_diff.min_value if the current element is smaller than min_value.max_diff.#include <vector>
#include <algorithm>
#include <iostream>
class Solution {
public:
int maximumDifference(std::vector<int>& nums) {
int min_value = nums[0];
int max_diff = -1;
for (int j = 1; j < nums.size(); ++j) {
if (nums[j] > min_value) {
max_diff = std::max(max_diff, nums[j] - min_value);
} else {
min_value = std::min(min_value, nums[j]);
}
}
return max_diff;
}
};
int main() {
Solution sol;
std::vector<int> nums = {7, 1, 5, 4};
std::cout << "Maximum Difference: " << sol.maximumDifference(nums) << std::endl;
return 0;
}
The time complexity of this solution is O(n), where n is the length of the input array. This is because we traverse the array only once.
The space complexity is O(1) since we use a fixed amount of extra space to store min_value and max_diff.
By maintaining these values during a single pass over the array, we ensure a performant solution that meets the problem constraints efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?