*Flower Bed
import java.util.ArrayList; public class solution{ public static boolean canPlaceFlowers(ArrayList<Boolean> arr, int count) { if(arr == null){ throw new NullPointerException(); } if(count>arr.size()) return false; if(arr.size()==1) { if(!arr.get(0))return true; else return false; } if(arr.size()==2) { if(count<=1&&!arr.get(0)&&!arr.get(1))return true; else return false; } int locations = 0; boolean lastPos=arr.get(0), thisPos=arr.get(0), nextPos=arr.get(0); int index = 2; while(index < arr.size()){ lastPos = arr.get(index-2); thisPos = arr.get(index-1); nextPos = arr.get(index); if(!(lastPos || thisPos || nextPos)){ arr.set(index-1,true); locations ++; if(locations >= count){ return true; } } index++; } if(index == arr.size() && !(thisPos || nextPos)){ locations++; } return locations >= count; } public static void main(String[] args) { ArrayList<Boolean> list = new ArrayList<Boolean>(); list.add(false); int no = 1; boolean res = canPlaceFlowers(list,no); System.out.println(res); } }
reference:
http://www.careercup.com/question?id=5119852580700160