[Hacker Rank] Minimum Loss

Minimum Loss

  • Time : O(nlogn)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
int minimumLoss(vector<long> A) {
long res = INT_MAX, n = A.size();
set<long> s;
for(int i = n - 1; i >= 0; i--) {
auto it = s.lower_bound(A[i]);
if(it != begin(s)) res = min(res, A[i] - *prev(it));
s.insert(A[i]);
}

return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/07/PS/HackerRank/minimum-loss/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.