1049 最大子段和


基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 取消关注
N个整数组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的连续子段和的最大值。当所给的整数均为负数时和为0。
例如:-2,11,-4,13,-5,-2,和最大的子段为:11,-4,13。和为20。
Input
第1行:整数序列的长度N(2 <= N <= 50000)
第2 - N + 1行:N个整数(-10^9 <= A[i] <= 10^9)
Output
输出最大子段和。
Input示例
6
-2
11
-4
13
-5
-2
Output示例
20


//注意,这里数据类型要用long
/*思路:从左到右,遍历一遍数组,我这里没有用数组,不过思路是一样的,用变量cur记录每一步的累加和,遍历到正数cur增加,遍历到负数cur减少,当cur<0,说明累加到当前数出现了小于0的结果,那么累加的这一部分一定不能作为产生最大累加和子数组的左边部分,此时令cur=0,表示重新从下一个数开始累加,当cur>=0时,每一次累加都可能是最大的累加和,所以,用另一变量max全程记录跟踪cur出现的最大值即可。 上面的思路摘自左神的《程序员代码面试指南》 */
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        //input
        //process
        long cur = 0; 
        long max = Integer.MIN_VALUE;
        for(int i=0; i<n; ++i){
            cur += sc.nextInt();
            max = Math.max(max, cur);
            cur = cur > 0 ? cur : 0;
        }
        //output
        System.out.println(max);
    }
}

1051 最大子矩阵和


基准时间限制:2 秒 空间限制:131072 KB 分值: 40 难度:4级算法题 收藏 关注
一个M*N的矩阵,找到此矩阵的一个子矩阵,并且这个子矩阵的元素的和是最大的,输出这个最大的值。
例如:3*3的矩阵:

-1 3 -1
2 -1 3
-3 1 2

和最大的子矩阵是:

3 -1
-1 3
1 2
Input
第1行:M和N,中间用空格隔开(2 <= M,N <= 500)。
第2 - N + 1行:矩阵中的元素,每行M个数,中间用空格隔开。(-10^9 <= M[i] <= 10^9)
Output
输出和的最大值。如果所有数都是负数,就输出0。
Input示例
3 3
-1 3 -1
2 -1 3
-3 1 2
Output示例
7


//思路:将矩阵转化成一维数组
import java.util.*;
public class Main{
   public static void main(String[] args){
       Scanner sc = new Scanner(System.in);
       int m = sc.nextInt();
       int n = sc.nextInt();
       //n行m列
       int[][] a = new int[n][m];
       //input
       for(int i=0; i<n; ++i)
           for(int j=0; j<m; ++j)
               a[i][j] = sc.nextInt();
       //process
       int max = Integer.MIN_VALUE;
       int cur = 0;
       int[] s = null;
       for(int i=0; i<n; ++i){
           s = new int[m];         
           for(int j=i; j<n; ++j){
               cur = 0;
               for(int k=0; k<m; ++k){
                   s[k] += a[j][k];
                   cur += s[k];
                   max = Math.max(max, cur);
                   cur = cur>0 ? cur : 0; 
               }
           }
       }
       //output
       System.out.println(max);
   }
}