• 53. Maximum Subarray最大子数组和


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

    给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

    A subarray is a contiguous part of an array.

    子数组 是数组中的一个连续部分。

    Example 1:示例 1:

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


    Example 2:示例 2:

    Input: nums = [1]
    Output: 1


    Example 3:示例 3:

    Input: nums = [5,4,-1,7,8]
    Output: 23
     

    Constraints:提示:

    1 <= nums.length <= 10^{5}
    -10^{4} <= nums[i] <= 10^{4}

     

    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.

    进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。

    C语言(超出时间限制)

    1. int maxSubArray(int* nums, int numsSize){
    2. int max=-10000,temp;
    3. for(int i=0;i
    4. {
    5. temp=nums[i];
    6. if(max
    7. {
    8. max=nums[i];
    9. }
    10. for(int j=i+1;j
    11. {
    12. temp+=nums[j];
    13. if(max
    14. {
    15. max=temp;
    16. }
    17. }
    18. }
    19. return max;
    20. }

    C语言:

    1. int maxSubArray(int* nums, int numsSize){
    2. int cur=nums[0];
    3. int max=nums[0];
    4. for(int i=1;i
    5. {
    6. if(cur+nums[i]>nums[i])
    7. {
    8. cur+=nums[i];
    9. }
    10. else
    11. {
    12. cur=nums[i];
    13. }
    14. if(max
    15. {
    16. max=cur;
    17. }
    18. }
    19. return max;
    20. }

    执行结果:通过

    执行用时:96 ms, 在所有 C 提交中击败了65.95%的用户

    内存消耗:11.9 MB, 在所有 C 提交中击败了94.63%的用户

    通过测试用例:209 / 209

    C语言:

    1. int maxSubArray(int* nums, int numsSize){
    2. int cur=0;
    3. int max=INT_MIN;
    4. for(int i=0;i
    5. {
    6. if(cur<=0)
    7. cur=nums[i];
    8. else
    9. cur+=nums[i];
    10. if(cur>max)
    11. max=cur;
    12. }
    13. return max;
    14. }

    执行结果:通过

    执行用时:88 ms, 在所有 C 提交中击败了97.43%的用户

    内存消耗:12.3 MB, 在所有 C 提交中击败了8.30%的用户

    通过测试用例:209 / 209

  • 相关阅读:
    javaweb基于ssm的仓库管理系统
    KIT107 Programming Assignment 1
    机试算法学习
    人工智能学习:ResNet神经网络(8)
    FFmpeg开发笔记(三十二)利用RTMP协议构建电脑与手机的直播Demo
    7年阿里测试岗,我眼中的阿里虽然不完美,但值得去学5年
    解释Java中的安全模型
    todolist案例——vue脚手架(1)
    什么是微服务?怎么测试?今天一次性讲清楚...
    【云原生 | 从零开始学Kubernetes】十二、k8spod的生命周期与容器钩子
  • 原文地址:https://blog.csdn.net/DXB2021/article/details/126008701