zoukankan      html  css  js  c++  java
  • Maximum Subarray

    1. Title

    Maximum Subarray

    2. Http address

    https://leetcode.com/problems/maximum-subarray/

    3. The question

    Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

    For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
    the contiguous subarray [4,−1,2,1] has the largest sum = 6.

     4 My code(AC)

     1     public int maxSubArray(int[] nums) {
     2      
     3         if ( nums == null || nums.length == 0)
     4             return 0;
     5         int contiguousMax[] = new int[nums.length];
     6         contiguousMax[0] = nums[0];
     7         for(int i = 1 ; i < nums.length; i++)
     8         {
     9             contiguousMax[i] = Math.max(contiguousMax[i-1] + nums[i], nums[i]);
    10         }
    11         int opt_cur = nums[0];
    12         for(int i = 1; i < nums.length; i++)
    13         {
    14             opt_cur = Math.max(opt_cur, contiguousMax[i]);
    15         }
    16         return opt_cur;
    17     }
    18     
    19     // Accepted
    20     public int maxSubArrayTwo(int[] nums) {
    21         
    22         if ( nums == null || nums.length == 0)
    23             return 0;
    24 
    25         int opt_cur = nums[0];
    26         int contiguousMax = nums[0];
    27         for(int i = 1; i < nums.length; i++)
    28         {
    29             contiguousMax = Math.max(contiguousMax + nums[i], nums[i]);
    30             opt_cur = Math.max(opt_cur, contiguousMax);
    31         }
    32         return opt_cur;
    33     }
  • 相关阅读:
    深入浅出JMS(二)--ActiveMQ简单介绍以及安装
    redis学习
    浏览器的渲染过程
    http请求
    常用正则表达式
    js继承的几种实现方式
    js中的浅拷贝和深拷贝
    webpack常用的plugin
    linux基本命令
    webpack压缩代码组件uglifyjs-webpack-plugin
  • 原文地址:https://www.cnblogs.com/ordili/p/4970049.html
Copyright © 2011-2022 走看看