zoukankan      html  css  js  c++  java
  • [LeetCode] 53. Maximum Subarray

    Description

    Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

    Example:

    Input: [-2,1,-3,4,-1,2,1,-5,4],
    Output: 6
    Explanation: [4,-1,2,1] has the largest sum = 6.
    

    Follow up:

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

    Analyse

    找出一个数组连续子序列的最大和

    子序列要求连续,子序列向右扩展分为两种情况

    1. 将新元素加入子序列,子序列长度+1
    2. 抛弃之前的子序列,新元素成为新的子序列,子序列长度为1

    子序列的局部最大和为这两种情况中和最大的那个

    在所有的局部最大和中找出全局最大和

    写出一个算法复杂度为(O(n))的版本

    int maxSubArray(vector<int>& nums)
    {
        int max = nums[0], global_max = nums[0];
        int len = nums.size();
        for (int i = 1; i < len; i++) {
            max = max > 0 ? nums[i] + max : nums[i];
            global_max = max > global_max ? max : global_max;
        }
        return global_max;
    }
    
  • 相关阅读:
    字段名删不掉
    刷新f5/ctrl+f5
    大量数据模拟
    sub_query join drupal7 view_query_alter
    测试风格的代码
    csv/excel乱码
    window.location.reload(true)的异步现象
    扫描条形码
    yield %%% generator
    batch example
  • 原文地址:https://www.cnblogs.com/arcsinw/p/12913102.html
Copyright © 2011-2022 走看看