c_cpp 53.最大子阵列

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 53.最大子阵列相关的知识,希望对你有一定的参考价值。

//Runtime: 16 ms, faster than 20.14%
//Memory Usage: 10.3 MB, less than 60.30%

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        if(nums.empty()) return NULL;
        if(nums.size() == 1) return nums[0];
        
        int sum = 0;
        int maxSum = INT_MIN;
        
        for(int i = 0;i < nums.size();++i){
            for(int j = i;j < nums.size();++j){
                if(sum >= 0){
                    sum += nums[j];
                    if(sum >= maxSum)
                        maxSum = sum;
                }
                else 
                    break;
                // cout << "nums = " << nums[j] << endl;
                // cout << "maxSum = " << maxSum << " "<< "sum = " << sum << endl;
                // cout << "-------" << endl;
            }
            sum = 0;
        }
        return maxSum;
    }
};
//Runtime: 16 ms, faster than 20.14%
//Memory Usage: 10.4 MB, less than 40.32%

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

以上是关于c_cpp 53.最大子阵列的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 最大子阵列和子序列

c_cpp 最大乘积子阵列

c_cpp 最大子阵列总和。在具有最大总和的数组(包含至少一个数字)中查找连续的子数组。

java 53.最大子阵列(第1个).java

java 53.最大子阵列(第1个).java

java 53.最大子阵列(第1个).java