Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created May 24, 2020 21:21
Show Gist options
  • Save misterpoloy/5658d550b2ac6d26d87110a4356bd456 to your computer and use it in GitHub Desktop.
Save misterpoloy/5658d550b2ac6d26d87110a4356bd456 to your computer and use it in GitHub Desktop.
#CodeChallenge Longest continues range from start to end in an array
#include <vector>
#include <unordered_map>
#include <climits>
using namespace std;
vector<int> largestRange(vector<int> array) {
vector<int> longestRange;
unordered_map<int, bool> arrayMap;
int longestLength = INT_MIN;
// Inicializate to true for start counting;
for (int numb : array) {
arrayMap[numb] = true;
}
for (int numb : array) {
// Don't check for alreadychecked numbers
if (arrayMap[numb] == false) continue;
arrayMap[numb] = false;
// If exist increment the left one value
int left = numb - 1;
int right = numb + 1;
int currentLength = 0;
while (arrayMap.find(left) != arrayMap.end()) {
arrayMap[left] = false;
currentLength++;
left--;
}
while (arrayMap.find(right) != arrayMap.end()) {
arrayMap[right] = false;
currentLength++;
right++;
}
if (longestLength < currentLength) {
longestLength = currentLength;
longestRange = { left + 1, right - 1 };
}
}
return longestRange;
}
@misterpoloy
Copy link
Author

CodeChallenge

explanation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment