HackerRank The Maximum Subarray

36 篇文章 0 订阅
6 篇文章 0 订阅

原题网址:https://www.hackerrank.com/challenges/maxsubarray

Given an array  of  elements, find the maximum possible sum of a

  1. Contiguous subarray
  2. Non-contiguous (not necessarily contiguous) subarray.

Empty subarrays/subsequences should not be considered.

Input Format

First line of the input has an integer  cases follow. 
Each test case begins with an integer . In the next line,  integers follow representing the elements of array .

Constraints:

The subarray and subsequences you consider should have at least one element.

Output Format

Two, space separated, integers denoting the maximum contiguous and non-contiguous subarray. At least one integer should be selected and put into the subarrays (this may be required in cases where all elements are negative).

Sample Input

2 
4 
1 2 3 4
6
2 -1 2 3 4 -5

Sample Output

10 10
10 11

Explanation

In the first case: 
The max sum for both contiguous and non-contiguous elements is the sum of ALL the elements (as they are all positive).

In the second case: 
[2 -1 2 3 4] --> This forms the contiguous sub-array with the maximum sum. 
For the max sum of a not-necessarily-contiguous group of elements, simply add all the positive elements.

方法:动态规划。

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner scanner = new Scanner(System.in);
        int t = scanner.nextInt();
        for(int i = 0; i < t; i++) {
            int n = scanner.nextInt();
            int num = scanner.nextInt();
            int maxContiguous = num;
            int maxNonContiguous = num;
            int sumContiguous = num;
            sumContiguous = Math.max(sumContiguous, 0);
            
            for(int j = 1; j < n; j++) {
                num = scanner.nextInt();
                maxNonContiguous = Math.max(maxNonContiguous, Math.max(maxNonContiguous + num, num));
                
                sumContiguous += num;
                maxContiguous = Math.max(maxContiguous, sumContiguous);
                sumContiguous = Math.max(sumContiguous, 0);
            }
            System.out.println(maxContiguous + " " + maxNonContiguous);
        }
       
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值