Created
November 11, 2016 13:04
-
-
Save sleemer/82bb9c8f0a267f7a8bce2752a602f14a to your computer and use it in GitHub Desktop.
Implementation of algorithm that solves 'And-Xor-Or' problem from hackerrank.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.hackerrank.com/challenges/and-xor-or | |
// Original statement could be simplified: ((M1&M2)^(M1|M2))&(M1^M2) == M1^M2 | |
public int MaxAndOrXor(string input) | |
{ | |
var numbers = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) | |
.Select(int.Parse) | |
.ToArray(); | |
var max = 0; | |
foreach (var pair in GetSmallestPairs(numbers)) | |
{ | |
max = Math.Max(max, pair.Item1 ^ pair.Item2); | |
} | |
return max; | |
} | |
private IEnumerable<Tuple<int, int>> GetSmallestPairs(int[] numbers) | |
{ | |
var stack = new Stack<int>(); | |
for (int i = 0; i < numbers.Length; i++) | |
{ | |
while (stack.Count > 0) | |
{ | |
yield return new Tuple<int, int>(stack.Peek(), numbers[i]); | |
if (stack.Peek() > numbers[i]) { stack.Pop(); } | |
else { break; } | |
} | |
stack.Push(numbers[i]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment