牛客——连续子数组的最大和
今天分享一道动态规划的题目,笔者使用了三种方法,后一种方法是前一种的优化版本,从牛客的测试反馈可以看到有些许的进步。
第一种方法:使用了一个全局变量进行最大和的记录。
但这种方法的问题在于,在主函数里面对子数组的开始位置使用for循环手动操作了,没有在process()方法里面把事情都做完,不是很优雅的code。并且该方法没有使用备忘录进行Memory
随后笔者对此进行优化
//运行时间:12ms 占用内存:9664KB
public static int FindGreatestSumOfSubArray(int[] array) {
if(array == null || array.length < 1 ) return 0;
maxValue = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
process(array,i,0);
}
return maxValue;
}
public static int maxValue = Integer.MIN_VALUE;
public static void process(int[] array,int cur,int val){
if(cur >= array.length) return ;
if(cur == array.length - 1 ) {
val += array[cur];
maxValue = Math.max(val,maxValue);
}else {
//停止
val += array[cur];
maxValue = Math.max(val,maxValue);
// 往右走
process(array,cur+1,val);
}
}
第二种方法,对手动for()来指定起始位置进行了优化,process()方法可以自己主动生成起始位置,这一次代码看上去进步了一些,还加入了备忘录。但是这个全局变量还是没能处理掉,导致每一次都需要有额外的空间度损失.
maxValue的比较次数也太多 :(其中有趣的一点在于,把备忘录里的默认值从Integer.MIN_VALUE改为-2000后
占用内存变小了:)
//运行时间:11ms
//超过78.60%用Java提交的代码
//占用内存:9732KB ---------------------》MIN_VALUE
//超过3.02%用Java提交的代码
//运行时间:11ms
//超过78.60%用Java提交的代码
//占用内存:9652KB -----------------------》 -2000
//超过5.95%用Java提交的代码
public static int FindGreatestSumOfSubArray(int[] array) {
if(array == null || array.length < 1 ) return 0;
maxValue = Integer.MIN_VALUE;
int[][] dp = new int[array.length][array.length];
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[0].length; j++) {
dp[i][j] = -2000;
}
}
process(array,0,0,0,dp);
return maxValue;
}
public static int maxValue = Integer.MIN_VALUE;
public static void process(int[] array,int head,int cur,int val,int[][] dp){
if(cur >= array.length) return;
maxValue = Math.max(dp[head][cur],maxValue);
if(cur == array.length - 1 ) {
val += array[cur];
dp[head][cur] = val;
maxValue = Math.max(dp[head][cur],maxValue);
}else {
//停止
val += array[cur];
dp[head][cur] = val;
maxValue = Math.max(dp[head][cur],maxValue);
// 往右走
process(array,head,cur+1,val,dp);
process(array,cur+1,cur+1,0,dp);
}
}
第三种方法,这个方法终于把全局变量消除,最后通过返回值的比较来进行优化
//运行时间:12ms
//超过70.70%用Java提交的代码
//占用内存:9608KB
//超过7.85%用Java提交的代码
public static int FindGreatestSumOfSubArray(int[] array) {
if(array == null || array.length < 1 ) return 0;
int[][] dp = new int[array.length][array.length];
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[0].length; j++) {
dp[i][j] = -2000;
}
}
return process(array,0,0,0,dp);
}
public static int process(int[] array,int head,int cur,int val,int[][] dp){
if(cur >= array.length) return 0;
if(dp[head][cur] != -2000) return dp[head][cur];
if(cur == array.length - 1 ) {
val += array[cur];
dp[head][cur] = val;
return dp[head][cur];
}else {
//停止
val += array[cur];
dp[head][cur] = val;
// 往右走
int p1 = process(array,head,cur+1,val,dp);
int p2 = process(array,cur+1,cur+1,0,dp);
return Math.max(Math.max(dp[head][cur],p1),p2);
}
}