Leetcode 53 Maximum Subarray Sum
Given an array of integers nums
, please find a continuous subarray with the maximum sum (the subarray contains at least one element), and return its maximum sum.
A subarray is a contiguous part of an array.
Example 1:
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
Example 2:
输入:nums = [1]
输出:1
Example 3:
输入:nums = [5,4,-1,7,8]
输出:23
Solution 1: Dynamic programming
code:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
用一个变量pre来存储到i前面的所有最大子数和
用一个变量maxAns来从每次获得的pre中寻找最大值
int pre=0,maxAns=nums[0];
int n=nums.size();
for(int i=0;i<n;i++)
{
pre=fmax(pre+nums[i],nums[i]);
maxAns=fmax(maxAns,pre);
}
return maxAns;
}
};
Problem-solving ideas:
The fmax() function is a library function of the cmath header to find the maximum value of a given number , it takes two numbers and returns the larger one. fmax() function Syntax: fmax(x, y); Parameters: x, y – are the numbers used to find the larger value.
Use for loop to traverse, pre represents the largest sub-array sum before i, and after i, pre+nums[i] may not be as large as nums[i] alone, so after the loop traversal ends, maxAns stores i The value of the sum of consecutive subarrays with the largest sum in the number. Finally return.
Solution 2: Greedy
code:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n=nums.size();
if (n==0)
{
return 0;
}
//res表示当前具有的连续子数组最大和
//cur表示当前选择的子数组和
//INT_MIN -2^31,通常定义在头文件limits.h中
//C/C++中,所有超过该限值的数,都会出现溢出
int res=INT_MIN,cur=0;
for (int i=0;i<n;i++){
cur+=nums[i];
if(cur>res){
res=cur;
}
if(cur<0)
{
cur=0;
}
}
return res;
}
};
Problem-solving ideas:
Set a variable res to represent the maximum sum of the current continuous sub-arrays, set the initial value to INT_MIN, cur represents the sum of the currently selected sub-arrays, use the for loop to traverse, and add each element in turn, here set two judgment conditions, if(cur>res), then res=cur, if cur<0, set it to 0, (because cur plus negative numbers will only get smaller and smaller, which does not meet the topic of finding the maximum sum of continuous sub-arrays).