zoukankan      html  css  js  c++  java
  • LeetCode -- 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.

    click to show more practice.

    More practice:

    If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

    Analysis:

    在一个数组(至少包含一个元素)中找出一个连续的子数组 使该子数组有最大的和。

    例如:给出数组[-2, 1, -3, 4, -1, 2, 1, -5, 4],则其中连续的子数组是[4, -1, 2, 1],对应的和为sum = 6.

    更多的挑战:

    如果你找到了O(n)的解,可以尝试使用分治法来解决这个问题。

    思路:

    这种典型的求最大和最大积的问题,显然应该使用Dynamic Programming,关键在于找到一个通式。对于这个问题,要注意的是当目前数组元素的值大于之前累计的和时,当前数组元素的值应该作为新的起点;然后更新记录最终结果的变量。

    通式为:

    s = max(s + nums[i], nums[i]);

    sum = max(sum, s);

    Answer:

    public class Solution {
        public int maxSubArray(int[] nums) {
            if(nums == null || nums.length == 0)
                return 0;
            int sum = nums[0];
            int s = nums[0];
            for(int i=1; i<nums.length; i++) {
                s = Math.max(s + nums[i], nums[i]);
                sum = Math.max(sum, s);
            }
            return sum;
        }
    }
      
  • 相关阅读:
    MySQL之视图
    C# 学习笔记(二) 时间格式化字符串
    C# 学习笔记(一) Winform利用Assembly反射动态创建窗体
    puppet 4.4 System Requirements
    Linux下MySql启动时报错
    Linux Iptables
    Nginx Configure时配置
    Wireshark 使用教程
    Linux 下安装oracle数据库
    CaseFile
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5204447.html
Copyright © 2011-2022 走看看