• LeetCode 53. Maximum Subarray


    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.

     

    题目要求最大连续子数组的和,这里比较直接的思路是用动态规划,利用分治思想把问题进行拆分,我们用两个变量分别记录当前和最大和,如果当前和是负数,那么就可以把它舍弃直接用数组中的当前数字代替它即可,因为负数加上之后当前数字比当前数字更小,不如不加,代码如下:

     1 class Solution {
     2 public:
     3     int maxSubArray(vector<int>& nums) 
     4     {
     5         int nCurSum = 0;           //当前和
     6         int nGreatestSum = INT_MIN;  //最大和
     7         for (auto num : nums)
     8         {
     9             nCurSum = max(num, num + nCurSum);
    10             nGreatestSum = max(nCurSum, nGreatestSum);
    11         }
    12         return nGreatestSum;
    13     }
    14 };

    或者是不调用max函数,但是这样做并不能提高速度:

     1 class Solution {
     2 public:
     3     int maxSubArray(vector<int>& nums) 
     4     {
     5         int nCurSum = 0;
     6         int nGreatestSum = INT_MIN;
     7         for (auto num : nums)
     8         {
     9             if (nCurSum <= 0)
    10                 nCurSum = num;
    11             else
    12                 nCurSum += num;
    13             if (nCurSum > nGreatestSum)
    14                 nGreatestSum = nCurSum;
    15         }
    16         return nGreatestSum;
    17     }
    18 };
  • 相关阅读:
    js中操作Map集合
    js中json字符串与map的相互转化
    安卓开发--个人软件开发-day05
    javabean工具类方法lombok
    hadoop的datanode没有正常启动
    安卓开发--个人软件开发-day04
    安卓开发--个人软件开发-day03
    bigData学习笔记-hadoop总结
    spring框架学习之mybatis
    安卓开发--个人软件开发-day02
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8085076.html
Copyright © 2020-2023  润新知