思路:将序列累计求和并存入数组,将数组排序,计算相邻两个值之差,若差大于0且在原数组中两数前后顺序相同,则记录下两数之差,遍历一遍新数组,若有符合条件的差小于前一个,则将最小差记录下来
如:9,-3,-5,-7,11,7 累加得:0,9,6,1,-6,5,12
排序后得,-6,0,1,5,6,9,12, 后一位减前一位有 6,1,4,1,3,3
因为在原数组中,-6在0后,顾不可以,1在0后,顾可以,所以最小值为1
public static class Node{
public Node(){}
public int sum;
public int k;
}
public static int minPositiveSum(int[] a){
int len = a.length;
Node[] b = new Node[len + 1];
for(int i = 0; i < len+1; i++)
b[i] = new Node();
b[0].sum = 0;
b[0].k = 0;
for(int i=0; i < len; i++){
b[i+1].sum = b[i].sum + a[i];
b[i+1].k = i + 1;
}
sort(b);
int min = 65532;
int sum = 0;
for(int i = 0; i < len; i++){
sum = b[i+1].sum - b[i].sum;
if(b[i].k < b[i+1].k && sum > 0 && sum < min)
min = sum;
}
return min;
}
public static void sort(Node[] b){
int len = b.length;
int j = 0;
for(int gap = len/2;gap > 0;gap /= 2){
for(int i = gap; i < len ; i++){
Node tmp = b[i];
for(j = i ; j >= gap && b[j-gap].sum > tmp.sum ; j -= gap)
b[j] = b[j-gap];
b[j] = tmp;
}
}
}
分享: