CodeKnight
BAN USERThe same approach with corrections, need to return v[start] as its lowest version where bug could have been introduced.
Also in the else, we can start from mid+1
static int findbugIntroduced(int[] v,int start, int end)
{
if(start == end || end-start == 1) return v[start];//return the lowest, where the bug is introduced
int mid = (start+end)/2;
if(isBug(v[mid]))//then introduced in lower version or mid
{
return findbugIntroduced(v,start,mid);
}else
{
return findbugIntroduced(v,mid+1,end);//can do mid+1 as mid doesnt have bug
}
}
A simple sliding window will do the trick
static int[] vals = {23, 5, 4, 7, 2, 11};
static int target = 18;
static void findConsecutiveSum()
{
int i = 0; int j =1;
int l = vals.length;
int targ = vals[0];
while(i < l && j < l)
{
if(targ == target){
System.out.println("from index "+i+" to "+(j-1));
return;
}
if(targ < target)
{
targ = targ+vals[j];
j++;
}
if(targ > target)
{
targ = targ - vals[i];
i++;
}
}
}
static int targetI = 3;
static int targetJ = 2;
public static int minimumSteps = targetI * targetJ;
public static void minSteps(int i, int j, int depth)
{
if(depth > minimumSteps)
{
return;
}
if(i == targetI && j== targetJ){
minimumSteps = depth;
System.out.println("Number of steps "+minimumSteps);
}
minSteps(i+j, j, depth+1);
minSteps(i, i+j, depth+1);
}
public static void consecutivesum()
{
int[] ele = {1,3,5,7,9};
int target = 15;
int beginIdx= 0;
int endIdx = 1;
int tempSum = ele[beginIdx];
while(beginIdx <= endIdx && endIdx < ele.length)
{
if(tempSum == target)
{
System.out.print("{");
for(int i = beginIdx;i < endIdx;i++)
{
System.out.print(""+ele[i]);
}
System.out.print("}");
return;
}
if(tempSum < target)
{
tempSum += ele[endIdx];
endIdx++;
}
else{
tempSum -= ele[beginIdx];
beginIdx++;
}
}
System.out.println("No solution\n");
}
public static void maxProfit()
{
int[] stock = {10, 30, 42, 15, 20, 50, 10, 25};
int minIdx = 0;
int buyIdx = 0;
int sellIdx = 0;
int maxDiff = 0;
int j = 0;
while(j < stock.length)
{
if(stock[j] - stock[minIdx] > maxDiff)
{
maxDiff = stock[j] - stock[minIdx];
sellIdx = j;
buyIdx = minIdx;
}
else if(stock[j] < stock[minIdx])
{
minIdx = j;
}
j++;
}
System.out.println("buy"+stock[buyIdx]+"sell"+stock[sellIdx]);
}
public static void sortArraybyIdx()
{
char[] A = {'C', 'D', 'E', 'F', 'G'};
int[] B = {3, 0, 4, 1, 2};//DFGCE
int currIdx = 0;
int shldbeIdx = 0;
int k = 0;
while(k < B.length)
{
shldbeIdx = B[shldbeIdx];//3
currIdx = k;//0
//
char temp = A[shldbeIdx];
A[shldbeIdx] = A[currIdx];
A[currIdx] = temp;
//
int tempInt = B[shldbeIdx];
B[shldbeIdx] = B[currIdx];
B[currIdx] = tempInt;
if(B[currIdx] == k)
k++;
}
for(char l : A)
{
System.out.print(l);
}
}
Nice!!
- CodeKnight November 17, 2015