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     }
  • 相关阅读:
    我所认识的JavaScript
    谈如何边做事,边提高
    对JavaScript开发中困扰的思考
    Soundex语音算法
    Perl分割字符串的一个精妙的写法
    Perl深拷贝
    Git diff hash顺序的问题
    perl命令行批量修改文件内容
    IOS写文件
    删除Linux乱码文件
  • 原文地址:https://www.cnblogs.com/ordili/p/4970049.html
Copyright © 2011-2022 走看看