sriman2k
BAN USERpackage com.general;
public class FindSmallestDivisableNumberSum {
//write an algorithm to find sum of numbers which are smaller than N and divisible by 3 or 5
//Example:
//N = 9 => 3 + 5 + 6 = 14
//N = 10 => 3 + 5 + 6 + 9 = 23
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
FindSmallestDivisableNumberSum findsum=new FindSmallestDivisableNumberSum();
System.out.println("Total :::"+findsum.sum(11-1));
}
int sum(int n)
{
int sum=0;
if(n<=0)
{
return 0;
}
if(n%3==0 || n%5==0)
{
sum=sum+n;
n--;
}
else
{
n--;
}
return sum+sum(n);
}
}
Use the version number concept like ORM does.
Have your update statement where clause to include the version that you read.
update *** set f1= value,versionnum=versionnum+1 where versionnum=<<versionnumber that you read>>
If other thread already commited, this update will be a no op.
public class BuySellProblem {
/**
* @param args
*/
public static void main(String[] args) {
int tempProfit=0;
int commitProfit=0;
int tempBuy=0;
int tempSell=0;
int commitBuy=0;
int commitSell=0;
int[] input = {110 ,149 ,137, 147, 148, 151, 100};
for (int i = 0,j=1; j < input.length; i++,j++) {
int tempDiff=input[j]-input[i];
if(tempDiff>0)
{
tempProfit=tempProfit+tempDiff;
if(tempBuy==0){
tempBuy=input[i];
}
if(tempBuy>input[i]){
tempBuy=input[i];
}
tempSell=input[j];
if(commitProfit==0 &&commitBuy==0&&commitSell==0){
commitProfit=tempProfit;
commitBuy=tempBuy;
commitSell=tempSell;
}
if(commitBuy>tempBuy&&commitSell<tempSell)
{
commitBuy=tempBuy;
}
if( commitSell<tempSell)
{
commitSell=tempSell;
commitProfit=tempSell-tempBuy;
}
}
else
{
if(commitProfit==0 &&commitBuy==0&&commitSell==0){
commitProfit=tempProfit;
commitBuy=tempBuy;
commitSell=tempSell;
}
if(commitBuy>tempBuy&&commitSell<tempSell){
commitBuy=tempBuy;
}
if( commitSell<tempSell)
{
commitSell=tempSell;
commitProfit=tempSell-tempBuy;
}
tempProfit=0;
}
}
System.out.println("MaxBuy:"+commitBuy);
System.out.println("MaxSell:"+commitSell);
System.out.println("MaxProfit:"+commitProfit);
}
}
O(n)
- sriman2k September 25, 2013
Java Code for the above algorithm.
- sriman2k February 22, 2015