Skip to content

Commit

Permalink
Create smallest-range-ii.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Sep 23, 2018
1 parent 089b7b5 commit a61b88f
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions C++/smallest-range-ii.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Time: O(nlogn)
// Space: O(1)

class Solution {
public:
int smallestRangeII(vector<int>& A, int K) {
sort(A.begin(), A.end());
int result = A.back() - A.front();
for (int i = 0; i < A.size() - 1; ++i) {
result = min(result,
max(A.back() - K, A[i] + K) -
min(A.front() + K, A[i + 1] - K));
}
return result;
}
};

0 comments on commit a61b88f

Please sign in to comment.