zoukankan      html  css  js  c++  java
  • 53. 最大子序和

    题目描述:

      给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

      示例:

      输入: [-2,1,-3,4,-1,2,1,-5,4],
        输出: 6
      解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

    题解:

    public class L53 {
        public static int maxSubArray(int[] nums) {
            return getMaxSub3(nums,0,nums.length-1);
        }
        //使用动态规划方法
        public static int getMaxSub(int[] nums){
            int res = Integer.MIN_VALUE;
            //建立一个数组
            int maxSub0 = 0;
            for(int index = 0;index<nums.length;index++){
                if(index == 0 || (maxSub0 < 0)){
                    maxSub0 = nums[index];
                }else{
                    maxSub0 = maxSub0 +nums[index];
                }
                res = maxSub0 > res?maxSub0:res;
            }
            return res;
        }
        //使用贪心法--即遇到sum <0,时候将其值置0
        public static int getMaxSub2(int[] nums){
            int res = Integer.MIN_VALUE;
            //建立一个数组
            int maxSub0 = 0;
            for(int index = 0;index<nums.length;index++){
                maxSub0 = maxSub0 +nums[index];
                res = maxSub0 > res?maxSub0:res;
                if(maxSub0 <0){
                    maxSub0 = 0;
                }
            }
            return res;
        }
        //经典的分治法--待补充
        public static int getMaxSub3(int[] nums,int start,int end){
            if(end == start+1){
                return Math.max(nums[start],Math.max(nums[start] + nums[end],nums[end]));
            }else if(end == start){
                return nums[start];
            }
            int middle = (start + end)/2;
            int left = getMaxSub3(nums,start,middle);
            int right = getMaxSub3(nums,middle+1,end);
            int i = middle;int sumLeft = 0;int maxLeft = Integer.MIN_VALUE;
            int j = middle+1;int sumRight = 0;int maxRight = Integer.MIN_VALUE;
            while(i >= start){
                sumLeft += nums[i];
                maxLeft = Math.max(sumLeft,maxLeft);
                i--;
            }
            while(j <= end){
                sumRight += nums[j];
                maxRight = Math.max(maxRight,sumRight);
                j++;
            }
            return Math.max(maxLeft+maxRight,Math.max(left,right));
        }
        public static void main(String[] args) {
            int nums[] = {-2,-1,-3};
            System.out.println(maxSubArray(nums));
        }
    }
  • 相关阅读:
    APP开发关于缓存
    SlidingMenu+Fragment实现当前最流行的侧滑
    深入理解dp px density
    HDU1847--Good Luck in CET-4 Everybody!(SG函数)
    【转】博弈论——acm
    HDU1846--Brave Game(巴什博弈)
    HDU2179--pi(麦金公式)
    HDU1026--Ignatius and the Princess I(BFS记录路径)
    HDU1237--简单计算器(栈的应用)
    HDU3398—String-(组合数)
  • 原文地址:https://www.cnblogs.com/mayang2465/p/11982280.html
Copyright © 2011-2022 走看看