Last active
August 29, 2015 14:17
-
-
Save vjames19/f8f7e8d819eaba9b4310 to your computer and use it in GitHub Desktop.
Largest block of ones divide and conquer
This file contains hidden or 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
package com.vjames19; | |
/** | |
* Created by vjames19 on 3/16/15. | |
*/ | |
public class LargestBlockOfOnes { | |
public static int[] largestBlockOfOnes(int[] a, int low, int sup) { | |
if (low > sup) { | |
return new int[] {-1, -1}; | |
} | |
if (low == sup) { | |
if (a[low] == 1) { | |
return new int[] {low, low}; | |
} else { | |
return new int[] {-1, -1}; | |
} | |
} else { | |
int mid = (low + sup) / 2; | |
int[] left = largestBlockOfOnes(a, low, mid); // Solution of the left portion. | |
int[] right = largestBlockOfOnes(a, mid + 1, sup); // Solution of the right portion. | |
// Checking for cross boundary solution only if there are ones in the boundaries; | |
int[] middle = new int[]{-1, -1}; // Default solution if there is no cross boundary solution. | |
if (a[mid] == 1 && a[mid + 1] == 1) { | |
int i = mid, j = mid; | |
while(i >= low && a[i] == 1) { // Inspect the left side of the boundary. | |
i--; | |
} | |
while (j <= sup && a[j] == 1) { // Inspect the right side of the boundary. | |
j++; | |
} | |
// Update the indexes since we went past the block boundary by one. | |
middle[0] = i + 1; | |
middle[1] = j - 1; | |
} | |
// Return the index array with the biggest range. | |
// Ranges will be >= 0 | |
int leftRange = left[1] - left[0]; | |
int rightRange = right[1] - right[0]; | |
int middleRange = middle[1] - middle[0]; | |
int max = Math.max(leftRange, rightRange); | |
max = Math.max(max, middleRange); | |
if (max == leftRange) { | |
return left; | |
} else if (max == rightRange) { | |
return right; | |
} else { | |
return middle; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment