class="java" name="code">
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @version 0.1
* @author QuarterLifeForJava
* 说明:1.思路见程序下面的图
* 2.未经大量反复测试
* 3.必有更好更精简方式,你可以写的更好
*/
public class Test {
//简单测试下
public static void main(String[] args) {
int test1[] = new int[]{3,1,1,3,5,1,6,8,1,4,6,2,6};
System.out.println(core(test1));
int test2[] = new int[]{1,2,3,4,5};
System.out.println(core(test2));
int test3[] = new int[]{5,4,3,2,1};
System.out.println(core(test3));
int test4[] = new int[]{5,4,3,2,1,2,3};
System.out.println(core(test4));
int test5[] = new int[]{5,4};
System.out.println(core(test5));
int test6[] = new int[]{3,9,4,8,1,1,1,3};
System.out.println(core(test6));
}
//核心处理
public static int core(int array[]){
int capacity = 0;//容量
int temp[] = Arrays.copyOf(array, array.length);
StringBuilder sb = new StringBuilder();
if(array.length<3){
return capacity;
}else{
for (int i = 0; i < array.length; i++) {
if(i==array.length-1){
temp[array.length-1] = 0;
sb.append(temp[array.length-1]);
break;
}
if(array[i]>array[i+1]){
temp[i] = 0;//0高
}else{
temp[i] = 1;//1低
}
sb.append(temp[i]);
}
}
int length = sb.toString().length();
Pattern p = Pattern.compile("0+1+0");
Matcher m = p.matcher(sb.toString());
while(m.find()){
capacity+=calculateEach(array, m.start(), m.end()-1);
m.region(m.end()-1, length);
}
return capacity;
}
//计算每组匹配
public static int calculateEach(int array[],int start,int end){
int temp = 0;
int count = 0;
if(array[start]>=array[end]){
temp = array[end];
}else{
temp = array[start];
}
for (int i = start+1; i < end; i++) {
//特殊处理类似5,4,7,8,9的情况
count+=((temp-array[i]<=0)?0:(temp-array[i]));
}
return count;
}
}
- 大小: 145.8 KB