Created
September 20, 2019 00:07
-
-
Save summit87/131e9e047752e6d7565f72d045dc0556 to your computer and use it in GitHub Desktop.
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.practice.backtracking.mattrix; | |
| public class RowWithMax1s { | |
| public static void main(String[] args) { | |
| int[][] mat = {{0, 0, 0, 1}, | |
| {0, 0, 0, 0}, | |
| {0, 0, 0, 1}, | |
| {0, 1, 1, 1} | |
| }; | |
| int max = Integer.MIN_VALUE; | |
| for (int i = 0; i < 4; i++) { | |
| int x = mat[i].length; | |
| int ind = binarySearch(mat[i], 0, x - 1); | |
| if (x - ind > max) { | |
| max = x - ind; | |
| } | |
| } | |
| System.out.println(max); | |
| // max1s(mat, 4, 4); | |
| } | |
| private static void max1s(int[][] mat, int row, int col) { | |
| int max_len = Integer.MIN_VALUE; | |
| int k = 0; | |
| for (int i = 0; i < row; i++) { | |
| int x = 0; | |
| for (int j = x; j < col; ) { | |
| if (mat[i][j] == 1) { | |
| x = j; | |
| k = j; | |
| if (max_len < col - x) { | |
| max_len = col - x; | |
| } | |
| while (k > 0 && mat[i][k] == 1) { | |
| k--; | |
| x--; | |
| } | |
| if (j == col - 1) { | |
| k = 0; | |
| } | |
| break; | |
| } else { | |
| j++; | |
| } | |
| } | |
| } | |
| System.out.print(max_len); | |
| } | |
| private static int binarySearch(int[] a, int left, int right) { | |
| if (left == right) { | |
| return left; | |
| } | |
| int mid = (left + right) / 2; | |
| if (mid + 1 <= right && a[mid] == 0 && a[mid + 1] == 1) { | |
| return mid + 1; | |
| } | |
| if (mid - 1 >= 0 && a[mid] == 1 && a[mid - 1] == 0) { | |
| return mid; | |
| } | |
| if (mid + 1 <= right && a[mid] == 1) { | |
| return binarySearch(a, left, mid); | |
| } | |
| return binarySearch(a, mid + 1, right); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment