Tech Qu: Maximum sub sequence which has equal number of 1s and 0s.
You are given an array ' containing 0s and 1s. Find the maximum sub sequence which has equal number of 1s and 0s.
The solution is straight forward (using a long so testing would be easy).
- We determine the maximum possible length and use this to shorten the loops.
Code Snippet
- public static int Subsequence(long rawdata)
- {
- var data = new BitArray(System.BitConverter.GetBytes(rawdata));
- if (data.Length < 2)
- return data.Length;
- var zCount = 0;
- var oneCount = 0;
- var sb = new StringBuilder();
- foreach (bool datum in data)
- {
- if (datum)
- {
- oneCount++;
- sb.Append("1");
- }
- else
- {
- zCount++;
- sb.Append("0");
- }
- }
- var endSearch =2 * Math.Min(oneCount, zCount);
- var maxlength = 0;
- var index = 0;
- for (int i = 0; i < data.Length; i++)
- {
- var count = 0;
- for (int j = i; j < Math.Min( i + endSearch,data.Length); j++)
- {
- count += data[j] ? 1 : -1;
- if (count == 0 && maxlength < j-i)
- {
- maxlength = j - i +1;
- index = j;
- }
- }
- }
- Console.WriteLine(String.Format("{0}:{1} --> {2}",
- rawdata,
- sb,
- maxlength));
- return maxlength;
- }
The test was done by just walking values and spot checking.
Code Snippet
- for(long i=1; i < 32; i++)
- {
- Questions.Subsequence(i);
- }
The example for 17, yielding just 2 appears to confirm correctness.
Comments
Post a Comment