Let's define an array as "pointy" if it monotonically increases from element to some element k and then monotonically decreases from k onwards. (0 <= k).
Example: [1,2,3,4,5,4,3,1]
Not Pointy: [1,2,3,5,3,6,1]
Given an array "s", modify it so that it is pointy.
MySolution:
public class Pointy {
public boolean isPointy(int array[])
{
boolean isdecreasing=false;
int current=array[0];
boolean finalres=false;
int index=0;
for(int i=1;i<array.length;i++)
{
if(current<=array[i])
{
current=array[i];
}
else
{
index=i-1;
isdecreasing=true;
}
if(isdecreasing)
{
finalres=passing(index,array);
break;
}
}
return finalres;
}
public boolean passing(int index,int array1[])
{
boolean res=false;
for(int i=index+1,j=1;i<array1.length;i++,j++)
{
if(array1[index-j]!=array1[i])
{
break;
}
//if there is
if(i == array1.length-1)
res=true;
}
return res;
}
//main method
public static void main(String args[])
{
Pointy p=new Pointy();
int ar[]={1,2,3,5,3,6,1};
if(p.isPointy(ar))
System.out.print("It is pointy");
else
System.out.print("It is not a pointy ");
}
}
output:
--------------------------
It is not a pointy
Example: [1,2,3,4,5,4,3,1]
Not Pointy: [1,2,3,5,3,6,1]
Given an array "s", modify it so that it is pointy.
MySolution:
public class Pointy {
public boolean isPointy(int array[])
{
boolean isdecreasing=false;
int current=array[0];
boolean finalres=false;
int index=0;
for(int i=1;i<array.length;i++)
{
if(current<=array[i])
{
current=array[i];
}
else
{
index=i-1;
isdecreasing=true;
}
if(isdecreasing)
{
finalres=passing(index,array);
break;
}
}
return finalres;
}
public boolean passing(int index,int array1[])
{
boolean res=false;
for(int i=index+1,j=1;i<array1.length;i++,j++)
{
if(array1[index-j]!=array1[i])
{
break;
}
//if there is
if(i == array1.length-1)
res=true;
}
return res;
}
//main method
public static void main(String args[])
{
Pointy p=new Pointy();
int ar[]={1,2,3,5,3,6,1};
if(p.isPointy(ar))
System.out.print("It is pointy");
else
System.out.print("It is not a pointy ");
}
}
output:
--------------------------
It is not a pointy
Không có nhận xét nào:
Đăng nhận xét