题目大意:从小朋友一数组的糖个数 例如:[1,3,4,2,1,4,3],小朋友不能拿相邻两个位置的糖,求解最大糖数。
Java实现逻辑:
public class TestMahon {
public static void main(String[] args){
int[] candy =new int[]{1,5,3,1,7};
int sumMax =0;
for(int i =0;i
sumMax = Math.max(sumMax,findMax(candy,i,i));
}
System.out.println(sumMax);
}
private static int findMax(int[] candy,int startIndex,int lastSelectIndex){
int maxCount =0;
int tempCount =0;
for(int i = startIndex;i
if(Math.abs(i-lastSelectIndex)==1){
continue;
}
int lastSelect = i;
if(i==candy.length-1||i==candy.length-2){
tempCount = candy[i];
}else{
tempCount = candy[i]+ findMax(candy,++i,lastSelect);
}
maxCount = Math.max(maxCount,tempCount);
}
return maxCount;
}
}
用的递归的方式,做了全遍历。
网友评论