zoukankan      html  css  js  c++  java
  • Maximum Subarray

    Given an array of integers, find a contiguous subarray which has the largest sum. Notice The subarray should contain at least one number. Example Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6. Challenge Can you do it in time complexity O(n)?

    Analyse: For each element in that array, it has two choices: combine with its former or not. The max sum from start to an element is only related to the max sum of its former element. For example, in the given array above, the max sum from -2 to 4 is only related to the max sum from -2 to -3, has no relation to elements after 4.

    Therefore, it's a DP problem. The equation is: dp[i] = max(dp[i - 1] + nums[i], nums[i]).

    Runtime: 36ms

     1 class Solution {
     2 public:    
     3     /**
     4      * @param nums: A list of integers
     5      * @return: A integer indicate the sum of max subarray
     6      */
     7     int maxSubArray(vector<int> nums) {
     8         // write your code here
     9         if (nums.empty()) return 0;
    10         
    11         int n = nums.size();
    12         vector<int> dp(n, 0);
    13         dp[0] = nums[0];
    14         int maxSum = nums[0];
    15         for (int i = 1; i < n; i++) {
    16             dp[i] = max(dp[i - 1] + nums[i], nums[i]);
    17             maxSum = max(maxSum, dp[i]);
    18         }
    19         return maxSum;
    20     }
    21 };
  • 相关阅读:
    CentOS离线状态下安装Python3.7.0
    SQL练习题
    ajax的工作原理
    总结 XSS 与 CSRF 两种跨站攻击
    转css中文英文换行、禁止换行、显示省略号
    vue项目的搭建
    转axios 的应用
    rem布局计算(移动端,pc端有兼容性)
    rem
    彻底弄懂css中单位px和em,rem的区别
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5789468.html
Copyright © 2011-2022 走看看