Thứ Tư, 1 tháng 10, 2014

java Programing problem.

problem:


 You have an array of 0's and 1's. Determine a window [L,R], such that if you flip the bits in that window, you will have maximum number of 1's in your array, and then output this number of 1's.


For eg:
Input array: 1 0 0 1 0 0 1
Output: 6
Explanation:
If you choose a window [1,5], your array becomes,
1 1 1 0 1 1 1
which gives the total number of 1's now 6. So, your program should output the number 6, i.e. the maximum number of 1's after choosing a window.

solution:
package com.shashi;
class Array
{
 private int arr[];
 public Array()
 {
  //if you are not specifing any size
  arr=new int[10];
 }
 public Array(int s)
 {
  arr=new int[s];
 }
 public void fill(int arr1[])
 {
  for(int i=0;i<arr1.length;i++)
   arr[i]=arr1[i];
 }
 public void getNoOnes(int wl,int wr)
 {
  for(int i=wl;i<=wr;i++)
  {
   if(arr[i]==0)
    arr[i]=1;
   else if(arr[i]==1)
    arr[i]=0;
  }
 }

 public int getCount()
 {
  int count=0;
  for(int i=0;i<arr.length;i++)
  {
   if(arr[i]==1)
    count+=1;
  }
  return count;
 }
}
public class ArrayWindow {
 public static void main(String []args)
 {
  Array a=new Array(7);
  int data[]={1,0,0,1,0,0,1};
  a.fill(data);
  a.getNoOnes(1, 5);
  System.out.print(a.getCount());
 
 }
}
output
------------------
6
 
 
 

Không có nhận xét nào:

Đăng nhận xét