Posts

Showing posts with the label Day7

Print given matrix in spiral form

Image
Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Concept: When we look at array indices, i) At top we have row as constant and column varying from left to right. ii) At right we have column as constant and row varying from top to bottom. iii) At bottom we have row as constant and column varying from right to left. iv) At left we have column as constant and row varying from bottom to top. Code: import java.util.*; public class Solution {          public static void main(String[] args) {         int[][] a ={{1,2,3,4,5,6},{7,8,9,10,11,12},{13,14,15,16,17,18}};         int m = a.length;         int n = a[0].length;                  int top = 0, bottom = m-1, left = 0, right = n-1;                ...

Find zeroes to be flipped so that number of consecutive 1's is maximized

Image
Input: arr[] = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1} m = 2 Output: 5 7 We are allowed to flip maximum 2 zeroes. If we flip arr[5] and arr[7], we get 8 consecutive 1's which is maximum possible under given constraints Input: arr[] = {1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1} m = 1 Output: 7 We are allowed to flip maximum 1 zero. If we flip arr[7], we get 5 consecutive 1's which is maximum possible under given constraints. Input: arr[] = {0, 0, 0, 1} m = 4 Output: 0 1 2 Since m is more than number of zeroes, we can flip all zeroes. Steps: It is based on sliding window method. The window at any time should consists of only m zeroes. If the zerocount is below m wr is incremented. If the zerocount is more wl is incremented. Code: import java.util.*; public class Solution {       public static void main(String[] args) {         int[] a = {1,1,0,1,1,0,0,1,1,1};         int m = 2;   ...