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));
        }
    }
  • 相关阅读:
    (转发)storm 入门原理介绍
    shell :将标准输出及标准错误输出写到指定文件
    shell循环(两个日期比较,改变某个特定日期来改变当前比较值)
    MongoDB基本操作
    (转)cenntos 安装mongodb
    通过spark sql 将 hdfs上文件导入到mongodb
    股票实战--线性回归
    Python PIL 的image类和numpy array之间的互换
    根据关键点的脸型的计算
    用反卷积(Deconvnet)可视化理解卷积神经网络还有使用tensorboard
  • 原文地址:https://www.cnblogs.com/mayang2465/p/11982280.html
Copyright © 2011-2022 走看看