Skip to content

2021. Brightest Position on Street 👍

  • Time: $O(n\log n)$
  • Space: $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
class Solution {
 public:
  int brightestPosition(vector<vector<int>>& lights) {
    int ans = INT_MAX;
    int maxBrightness = -1;
    int currBrightness = 0;
    map<int, int> line;

    for (const vector<int>& light : lights) {
      const int position = light[0];
      const int range = light[1];
      ++line[position - range];
      --line[position + range + 1];
    }

    for (const auto& [pos, brightness] : line) {
      currBrightness += brightness;
      if (currBrightness > maxBrightness) {
        maxBrightness = currBrightness;
        ans = pos;
      }
    }

    return ans;
  }
};
 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
class Solution {
  public int brightestPosition(int[][] lights) {
    int ans = Integer.MAX_VALUE;
    int maxBrightness = -1;
    int currBrightness = 0;
    Map<Integer, Integer> line = new TreeMap<>();

    for (int[] light : lights) {
      final int position = light[0];
      final int range = light[1];
      line.merge(position - range, 1, Integer::sum);
      line.merge(position + range + 1, -1, Integer::sum);
    }

    for (final int pos : line.keySet()) {
      final int brightness = line.get(pos);
      currBrightness += brightness;
      if (currBrightness > maxBrightness) {
        maxBrightness = currBrightness;
        ans = pos;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from sortedcontainers import SortedDict


class Solution:
  def brightestPosition(self, lights: list[list[int]]) -> int:
    ans = math.inf
    maxBrightness = -1
    currBrightness = 0
    line = SortedDict()

    for position, rg in lights:
      start = position - rg
      end = position + rg + 1
      line[start] = line.get(start, 0) + 1
      line[end] = line.get(end, 0) - 1

    for pos, brightness in line.items():
      currBrightness += brightness
      if currBrightness > maxBrightness:
        maxBrightness = currBrightness
        ans = pos

    return ans