數(shù)組查詢(xún)

數(shù)組查詢(xún)

Description

Given an array, the task is to complete the function which finds the maximum sum subarray, where you may remove at most one element to get the maximum sum.

給定一個(gè)數(shù)組,任務(wù)是完成查找最大和子數(shù)組的函數(shù),在這個(gè)函數(shù)中,可以刪除最多一個(gè)元素來(lái)獲得最大和。

Input

第一行為測(cè)試用例個(gè)數(shù)T;后面每?jī)尚斜硎疽粋€(gè)用例,第一行為用例中數(shù)組長(zhǎng)度N,第二行為數(shù)組具體內(nèi)容。

Output

每一行表示對(duì)應(yīng)用例的結(jié)果。

Sample Input

1
5
1 2 3 -4 5

Sample Output

11

Solution

public class DeleteOneGetMaxSum {

    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int caseNum = in.nextInt();

        for(int i = 0; i < caseNum; i++){
            int len = in.nextInt();
            int[] arr = new int[len];
            for(int j = 0; j < len; j++){
                arr[j] = in.nextInt();
            }
            System.out.println(deleteOneGetMaxSum(arr));
        }
    }

    public static int deleteOneGetMaxSum(int[] arr){
        int len = arr.length;
        int[] left = new int[len];
        int[] right = new int[len];
        left[0] = arr[0];
        int notDeleteMax = Integer.MIN_VALUE;
        for(int i = 1; i < len; i++){
            left[i] = Math.max(left[i - 1] + arr[i], arr[i]);
            notDeleteMax = Math.max(notDeleteMax, left[i]);
        }
        right[len - 1] = arr[len - 1];
        for(int i = len - 2; i >= 0; i--){
            right[i] = Math.max(right[i + 1] + arr[i], arr[i]);
            notDeleteMax = Math.max(notDeleteMax, right[i]);
        }

        int max = notDeleteMax;
        for(int i = 1; i < len - 1; i++){
            max = Math.max(left[i - 1] + right[i + 1], max);
        }
        return max;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容