Widest Vertical Area Between Two Points Containing No Points

Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area.
vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.
Note that points on the edge of a vertical area are not considered included in the area.
Example 1:
Input: points = [[8,7],[9,9],[7,4],[9,7]]
Output: 1

Approach

Java

import java.util.Arrays;
import java.util.Comparator;

public class WidestVerticalArea {
    public static void main(String[] args) {
        int[][] points = { { 87 }, { 99 }, { 74 }, { 97 } };
        System.out.println(maxWidthOfVerticalArea(points));
    }

    static int maxWidthOfVerticalArea(int[][] points) {
        // sort the array
        Arrays.sort(points, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1int[] o2) {
                if (o1[0] == o2[0])
                    return o1[1] - o2[1];
                return o1[0] - o2[0];
            }
        });

        int ans = 0;
        // iterate till the length of array
        for (int i = 0; i < points.length - 1; i++) {
            // update answer
            ans = Math.max(ans, points[i + 1][0] - points[i][0]);
        }
        return ans;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

//comparator used for sorting
static bool cmp(vector<int&avector<int&b)
{
    if (a[0] == b[0])
        return a[1] < b[1];
    return a[0] < b[0];
}
int maxWidthOfVerticalArea(vector<vector<int>> &points)
{

    //sort the array
    sort(points.begin(), points.end(), cmp);
    int ans = 0;

    //iterate till the length of array
    for (int i = 0; i < points.size() - 1; i++)
    {
        //update answer
        ans = max(ans, points[i + 1][0] - points[i][0]);
    }
    return ans;
}

int main()
{
    vector<vector<int>> points = {{87}, {99}, {74}, {97}};
    cout << maxWidthOfVerticalArea(points);
    return 0;
}


No comments:

Post a Comment