1. 程式人生 > 其它 >Acwing 每日一題126. 最大的和

Acwing 每日一題126. 最大的和

原題連結

思路

題目是要求子矩形的最大和。確定一個左上頂點和一個右下頂點可以確定一個矩形,要列舉這兩個點,總的複雜度為N^4
為簡化,可以選擇列舉上邊界和下邊界,此時可以確定一個矩形區域,然後可以將問題轉換為求一維陣列的最大連續和。

import java.util.*;
class Main{
    final static int INF = 0x3f3f3f3f;
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        int N = scanner.
nextInt(); int mapp[][] = new int[N+1][N+1]; for(int i = 1; i <= N; i++){ for(int j = 1; j <= N; j++){ mapp[i][j] = scanner.nextInt(); mapp[i][j] += mapp[i-1][j]; } } int f[] = new int[N+1]; int ans =
-INF; //列舉上邊和下邊 for(int top = 0; top < N; top++){ for(int bottom = top + 1; bottom <= N; bottom++){ for(int col = 1; col <= N; col++){ f[col] = mapp[bottom][col] - mapp[top][col]; } for(int col = 1
; col <= N; col++){ //求最大連續和 if(f[col-1] > 0) f[col] = f[col-1] + f[col]; ans = max(ans, f[col]); } } } System.out.print(ans); return; } public static int max(int a, int b){ return a > b ? a : b; } }