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;
        }
    }
      
  • 相关阅读:
    iSeries存储过程笔记
    最近做得的网站
    两个iSeries存储过程的示例
    索引的怪异问题
    Saas的概念感触
    asp.net 2.0的TextBox遭遇ReadOnly=True时ViewState不回传的问题
    网上看到的一句诗
    DB2/400到Oracle的迁移
    如何往自己的网站增加Asp.net Ajax
    default关键字作用
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5204447.html
Copyright © 2011-2022 走看看