• Maximum Subarray 解答


    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.

    Solution 1 -- DP

    New array dp[i] has the following meaning:

    dp[i] is the largest sum of subsequence (including nums[i]).

     1 public class Solution {
     2     public int maxSubArray(int[] nums) {
     3         if (nums == null || nums.length < 1)
     4             return 0;
     5         int length = nums.length, result = nums[0];
     6         int[] dp = new int[length];
     7         dp[0] = nums[0];
     8         for (int i = 1; i < length; i++) {
     9             dp[i] = Math.max(nums[i], nums[i] + dp[i - 1]);
    10             result = Math.max(result, dp[i]);
    11         }
    12         return result;
    13     }
    14 }

    Solution 2

    We can only use one variable instead of array.

     1 public class Solution {
     2     public int maxSubArray(int[] nums) {
     3         if (nums == null || nums.length < 1)
     4             return 0;
     5         int length = nums.length, result = nums[0], tmp = nums[0];
     6         for (int i = 1; i < length; i++) {
     7             tmp = Math.max(nums[i], nums[i] + tmp);
     8             result = Math.max(result, tmp);
     9         }
    10         return result;
    11     }
    12 }
  • 相关阅读:
    connect oralce
    monolog php
    js继承
    前后端交互-一些关于接口设计的思考
    zoom:1;
    H5的新特性及部分API详解
    软文参考
    seo细节
    seo每天要做的事情
    seo(每天要干的哪些事)
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4822777.html
Copyright © 2020-2023  润新知