g1401_1500.s1499_max_value_of_equation.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g1401_1500.s1499_max_value_of_equation;
// #Hard #Array #Heap_Priority_Queue #Sliding_Window #Queue #Monotonic_Queue
// #2022_03_21_Time_7_ms_(98.61%)_Space_105.2_MB_(79.40%)
/**
* 1499 - Max Value of Equation\.
*
* Hard
*
* You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi]
such that xi < xj
for all `1 <= i < j <= points.length`. You are also given an integer `k`.
*
* Return _the maximum value of the equation_ yi + yj + |xi - xj|
where |xi - xj| <= k
and `1 <= i < j <= points.length`.
*
* It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k
.
*
* **Example 1:**
*
* **Input:** points = \[\[1,3],[2,0],[5,10],[6,-10]], k = 1
*
* **Output:** 4
*
* **Explanation:** The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
*
* No other pairs satisfy the condition, so we return the max of 4 and 1.
*
* **Example 2:**
*
* **Input:** points = \[\[0,0],[3,0],[9,2]], k = 3
*
* **Output:** 3
*
* **Explanation:** Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
*
* **Constraints:**
*
* * 2 <= points.length <= 105
* * `points[i].length == 2`
* * -108 <= xi, yi <= 108
* * 0 <= k <= 2 * 108
* * xi < xj
for all `1 <= i < j <= points.length`
* * xi
form a strictly increasing sequence.
**/
public class Solution {
public int findMaxValueOfEquation(int[][] points, int k) {
int res = Integer.MIN_VALUE;
int max = Integer.MIN_VALUE;
int r = 0;
int rMax = 0;
for (int l = 0; l < points.length - 1; l++) {
if (rMax == l) {
max = Integer.MIN_VALUE;
r = l + 1;
rMax = r;
}
while (r < points.length && points[r][0] - points[l][0] <= k) {
int v = points[r][0] + points[r][1];
if (max < v) {
max = v;
rMax = r;
}
r++;
}
if (points[rMax][0] - points[l][0] <= k) {
res =
Math.max(
res,
points[rMax][0] - points[l][0] + points[rMax][1] + points[l][1]);
}
}
return res;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy