Leetcode-3143

Maximum Points Inside the Square

Time complexity: $O(n)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <vector>
#include <cstring>

class Solution {
public:
    int maxPointsInsideSquare(std::vector<std::vector<int>>& points, std::string s) {
        int n = points.size();
        std::vector<std::pair<int, int>> dist(n);
        for (int i = 0; i < n; ++i) {
            dist[i].first = std::max(std::abs(points[i][0]), std::abs(points[i][1]));
            dist[i].second = s[i] - 'a';
        }
        std::sort(dist.begin(), dist.end());
        
        int visited[26] = { 0 };
        int last = -1, max_idx = 0;
        int m = std::min(26, n);
        for (int i = 0; i < m; ++i) {
            if (visited[dist[i].second] == 0) {
                visited[dist[i].second] = 1;
                if (dist[i].first != last) {
                    max_idx = i;
                    last = dist[i].first;
                }
            }
            else {
                if (dist[i].first != last) {
                    return i;
                }
                return max_idx;
            }
        }
        return m;
    }
};

Leetcode-3143

Licensed under CC BY-NC-SA 4.0