DREAMMAKER的做题记录
2021年9月24日
1、最大子序和
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-subarray
暴力法
class Solution {
public int maxSubArray(int[] nums) {
int max = 0x80000000;//初始值定义为INT_MIN
int numsSize = int(nums.size());
for (int i = 0; i < numsSize; i++)
{
int sum = 0;
for (int j = i; j < numsSize; j++)
{
sum += nums[j];
if (sum > max)
{
max = sum;
}
}
}
return max;
}
}
作者:pinku-2
链接:https://leetcode-cn.com/problems/maximum-subarray/solution/zui-da-zi-xu-he-cshi-xian-si-chong-jie-fa-bao-li-f/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
动态规划
class Solution {
public int maxSubArray(int[] nums) {
int result = 0x80000000;
int numsSize = int(nums.size());
//因为只需要知道dp的前一项,我们用int代替一维数组
int dp(nums[0]);
result = dp;
for (int i = 1; i < numsSize; i++)
{
dp = max(dp + nums[i], nums[i]);
result = max(result, dp);
}
return result;
}
}
作者:pinku-2
链接:https://leetcode-cn.com/problems/maximum-subarray/solution/zui-da-zi-xu-he-cshi-xian-si-chong-jie-fa-bao-li-f/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
贪心法
class Solution {
public int maxSubArray(int[] nums) {
int MaxSum = nums[0];
int CurrentSum = 0;
for(int i = 0;i < nums.length;i++){
if(CurrentSum > 0){
CurrentSum += nums[i];
}
else{
CurrentSum = nums[i];
}
if(CurrentSum > MaxSum)
MaxSum = CurrentSum;
}
return MaxSum;
}
}