birinder.tiwana
BAN USERLock lock = new Lock();
Condition condition = lock.newCondition();
boolean isLockHeld=false;
int threadId=-1;
int lockCount;
public void lock(){
lock.lock();
if(isLockHeld){
if(threadId==Thread.currentThread.getId()){
lockCount++;
}else{
while(isLockHeld){
condition.await();
}
lockCount++;
threadId=Thread.currentThread().getId();
isLockHeld=true;
}
}
lock.unlock();
}
}
public void unlock(){
lock.lock();
if(isLockHeld && threadId==Thread.currentThread().getId()){
lockCount - -;
if(lockCount==0){
threadId=-1;
isLockHeld=false;
condition.notifyAll();
}
}
lock.unlock();
}
This can be done in O(n) time using DP... we just need to keep track of 4 variables and update them in each iteration.
totalPrev= total result previous value of n
total1cs=total numbers with 1 c in the last two positions
total2cs=total numbers with 2 c in the last two positions
totalBPrev=total numbers which already have b in them..
here is the code which included logic for updates (quite self explanatory so I am not writing it down) ...
public static int findStrings(int n){
if(n==0)
return 0;
if(n==1)
return 3;
if(n==2)
return 8;
int k=2;
int totalPrev=8;
int total1cs=2;
int total2cs=1;
int totalBPrev=4;
while(k<n){
k++;
int newTotal=3*totalPrev-totalBPrev-total2cs;
int t2csnew=total1cs;
total1cs=totalPrev-total1cs-total2cs;
total2cs=t2csnew;
totalBPrev=totalPrev;
totalPrev=newTotal;
}
return totalPrev;
}
Repjanicepdaniels1, Backend Developer at Accenture
I decided to become an entrepreneur and work for myself because I wasn't making the money I wanted to ...
Repdanielhlee542, Associate at ASAPInfosystemsPvtLtd
Hi i am an health information technician at Seamans Furniture.Expertise in medical assistance, staff development and training, and implementing ...
- birinder.tiwana August 21, 2016