[AlgoExpert] Largest Range

Largest Range

  • Time : O(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
#include <vector>
using namespace std;

vector<int> largestRange(vector<int> A) {
int mi = *min_element(begin(A), end(A)), ma = *max_element(begin(A), end(A)), len = 0, n = A.size();
int gap = -mi + 1;
vector<int> merge(ma + gap + 2, 0);
vector<int> res;

for(int i = 0; i < n; i++) {
int a = A[i] + gap, left = merge[a - 1], right = merge[a + 1];
if(merge[a]) continue;
merge[a] = merge[a - left] = merge[a + right] = right + left + 1;
if(merge[a] > len) {
len = merge[a];
res = {a - left - gap, a + right - gap};
}
}

// Write your code here.
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/12/PS/AlgoExpert/largest-range/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.