2016. Maximum Difference Between Increasing Elements #1814
-
Topics: Given a 0-indexed integer array nums of size Return the maximum difference. If no such Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum difference between two elements in an array such that the smaller element appears before the larger element. If no such pair exists, we should return -1. Approach
This approach efficiently tracks the smallest element encountered so far and checks each subsequent element to see if it forms a larger difference with this smallest element. The algorithm runs in linear time, O(n), where n is the number of elements in the array, as it processes each element exactly once. The space complexity is O(1) since only a few variables are used. Let's implement this solution in PHP: 2016. Maximum Difference Between Increasing Elements <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maximumDifference($nums) {
$n = count($nums);
$min_so_far = $nums[0];
$max_diff = -1;
for ($j = 1; $j < $n; $j++) {
if ($nums[$j] > $min_so_far) {
$diff = $nums[$j] - $min_so_far;
if ($diff > $max_diff) {
$max_diff = $diff;
}
}
if ($nums[$j] < $min_so_far) {
$min_so_far = $nums[$j];
}
}
return $max_diff;
}
// Example tests
echo maximumDifference([7, 1, 5, 4]) . "\n"; // Output: 4
echo maximumDifference([9, 4, 3, 2]) . "\n"; // Output: -1
echo maximumDifference([1, 5, 2, 10]) . "\n"; // Output: 9
?> Explanation:
This approach efficiently finds the maximum difference by maintaining the smallest element encountered so far and leveraging it to compute potential differences with subsequent elements, ensuring optimal performance. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum difference between two elements in an array such that the smaller element appears before the larger element. If no such pair exists, we should return -1.
Approach