zoukankan      html  css  js  c++  java
  • 最大连续子数组和(Java)

    1 问题描述

    给定一个整数数组,数组里可能有正数、负数和零。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。例如,如果输入的数组为{1,-2,3,10,-4,7,2,-5},和最大的子数组为{3,10,-4,7,2},那么输出为该子数组的和18

     


    2 解决方案

    2.1 蛮力枚举法

    复制代码
    package com.liuzhen.array_2;
    
    public class MaxSubArray {
        
        public int bruteMethod(int[] A){
            int maxResult = A[0];        
            int maxTemp = 0;;
            for(int i = 0;i < A.length;i++){
                for(int j = i;j < A.length;j++){
                    for(int k = i;k <= j;k++){
                        maxTemp += A[k];
                    }
                    if(maxTemp > maxResult)
                        maxResult = maxTemp;
                    maxTemp = 0;             //完成一个子序列求和后,重新赋值为0
                }
            }
            return maxResult;
        }
        
        public static void main(String[] args){
            MaxSubArray test = new MaxSubArray();
            int[] A = {1,-2,3,10,-4,7,2,10,-5,4};
            System.out.println("使用蛮力法求解数组A的最大连续子数组和为:"+test.bruteMethod(A));
        }
    }
    复制代码

    运行结果:

    使用蛮力法求解数组A的最大连续子数组和为:28

    2.2 动态规划法

    复制代码
    package com.liuzhen.array_2;
    
    public class MaxSubArray {
        
        public int dynaticMethod(int[] A){
            int maxResult = A[0];   
            int maxTemp = 0;
            for(int i = 0;i < A.length;i++){
                if(maxTemp >= 0)
                    maxTemp += A[i];
                else
                    maxTemp = A[i];
                if(maxTemp > maxResult)
                    maxResult = maxTemp;
            }
            return maxResult;
        }
        
        public static void main(String[] args){
            MaxSubArray test = new MaxSubArray();
            int[] A = {1,-2,3,10,-4,7,2,10,-5,4};
            System.out.println("使用动态规划法求解数组A的最大连续子数组和为:"+test.dynaticMethod(A));
        }
    }
    复制代码

    运行结果:

    使用动态规划法求解数组A的最大连续子数组和为:28
  • 相关阅读:
    iaas,paas,saas理解
    July 06th. 2018, Week 27th. Friday
    July 05th. 2018, Week 27th. Thursday
    July 04th. 2018, Week 27th. Wednesday
    July 03rd. 2018, Week 27th. Tuesday
    July 02nd. 2018, Week 27th. Monday
    July 01st. 2018, Week 27th. Sunday
    June 30th. 2018, Week 26th. Saturday
    June 29th. 2018, Week 26th. Friday
    June 28th. 2018, Week 26th. Thursday
  • 原文地址:https://www.cnblogs.com/interdrp/p/13637878.html
Copyright © 2011-2022 走看看