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;
        }
    }
      
  • 相关阅读:
    springboot之redis的应用
    redis外部访问
    Calendar时间操作
    zookeeper安装
    springboot的interceptor(拦截器)的应用
    springboot中filter的用法
    IIS无法启动,应用程序池自动关闭
    HTTP 错误 403.14
    【转】JavaScript => TypeScript 入门
    angular2使用ng g component navbar创建组件报错
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5204447.html
Copyright © 2011-2022 走看看