leetcode日记(41)最大子数组和

以前大一的时候做过这题jpg,应该是个很经典的动态规划。

我首先的想法创建二维数组,横列代表起始位置纵列代表结束位置,依次补全数组,后来发现时间复杂度太高了:

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int n=nums.size();
        int t=0;
        int maxx=-2147483648;
        for(int i=0;i<n;i++){
            for(int j=i;j<n;j++){
                if(i==j) t=nums[i];
                else t+=nums[j];
                maxx=max(t,maxx);
            }
        }
        return maxx;
    }
};

发现答案只用一个循环,细想了一下终于明白了答案的思路,比上面要简洁得多

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int n=nums.size();
        int t=0;
        int maxx=nums[0];
        for(int i=0;i<n;i++){
            t=max(nums[i],t+nums[i]);
            maxx=max(maxx,t);
        }
        return maxx;
    }
};

答案的做法是只用两个int记录,一个记录二维数组中每一列中最大的数,一个记录最终结果。

相关推荐

  1. LeetCode[53]

    2024-07-16 15:20:02       59 阅读
  2. LeetCode 53

    2024-07-16 15:20:02       55 阅读
  3. 53. (力扣LeetCode

    2024-07-16 15:20:02       44 阅读
  4. leetcode 53

    2024-07-16 15:20:02       32 阅读
  5. leetcode 53.

    2024-07-16 15:20:02       29 阅读
  6. LeetCode例题讲解:

    2024-07-16 15:20:02       32 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-16 15:20:02       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-16 15:20:02       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-16 15:20:02       57 阅读
  4. Python语言-面向对象

    2024-07-16 15:20:02       68 阅读

热门阅读

  1. ssh升级

    ssh升级

    2024-07-16 15:20:02      24 阅读
  2. 什么是PHP?

    2024-07-16 15:20:02       22 阅读
  3. HDFS和ES

    2024-07-16 15:20:02       19 阅读
  4. 格雷编码

    2024-07-16 15:20:02       23 阅读
  5. 外呼系统用回拨模式打电话有什么优势

    2024-07-16 15:20:02       20 阅读
  6. datawhale【第二期】nlp

    2024-07-16 15:20:02       24 阅读
  7. DVC+Minio

    2024-07-16 15:20:02       19 阅读
  8. 力扣第208题“实现 Trie (前缀树)”

    2024-07-16 15:20:02       21 阅读
  9. 地暖管的选材

    2024-07-16 15:20:02       19 阅读
  10. easyexcel使用

    2024-07-16 15:20:02       20 阅读
  11. ubuntu报Unit firewalld.service could not be found.

    2024-07-16 15:20:02       18 阅读
  12. 【数据结构】BF和KMP算法

    2024-07-16 15:20:02       21 阅读
  13. 数据结构专项-字符串

    2024-07-16 15:20:02       19 阅读
  14. Python编程实例-使用urllib3进行HTTP请求详解

    2024-07-16 15:20:02       19 阅读