问题描述
小C发明了一款破冰游戏,在河面上有n块冰块,编号从1到n,企鹅站在某块冰块上,编号为K(用-1表示企鹅所在的冰块)。目标是通过破坏一些冰块,使企鹅掉落到河中。破坏冰块时需要根据冰块的强度进行操作,冰块两侧一旦没有与河岸连接,冰块就会掉落到河中。
每个冰块都有不同的强度 AiAi,表示需要的力量。为了使企鹅掉落到河中,必须破坏掉其两侧的冰块(即不能破坏企鹅所在的冰块)。目标是计算使企鹅掉落所需要的最小总力量。
例如,当冰块的强度 A=[7,−1,6,2,5]A=[7,−1,6,2,5] 且企鹅位于冰块 K=2K=2 时,破坏冰块1和冰块4分别需要力量7和2,总力量为9。
测试样例
样例1:
输入:
n = 5,A = [7, -1, 6, 2, 5]
输出:9
样例2:
输入:
n = 6,A = [4, -1, 3, 1, 8, 10]
输出:5
public class 破冰行动问题 {
public static int solution(int n, int[] A) {
// write code here
int min1=Integer.MAX_VALUE,min2=Integer.MAX_VALUE;
boolean find=false;
int i=0;
for(i=0;i<n;i++){
if(A[i]==-1){
find=true;
continue;
}
if(!find){
min1=Math.min(A[i],min1);
}else{
min2=Math.min(A[i],min2);
}
}
return min1+min2;
}
public static void main(String[] args) {
System.out.println(solution(5, new int[]{7, -1, 6, 2, 5}) == 9);
System.out.println(solution(6, new int[]{4, -1, 3, 1, 8, 10}) == 5);
System.out.println(solution(7, new int[]{9, 5, -1, 4, 6, 7, 2}) == 7);
}
}