LeetCode刷题实战53:最大子序和
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 最大子序和,我们先来看题面:
https://leetcode-cn.com/problems/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.
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.
题意
样例
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
解题
private int max = Integer.MIN_VALUE;
public int maxSubArray(int[] nums) {
int sum;
for (int i = 0; i < nums.length; i++) {// 子序列左端点
for (int j = i; j < nums.length; j++) {// 子序列右端点
sum = 0;
for (int k = i; k <= j; k++) {//暴力计算
sum += nums[k];
}
if (sum > max) {
max = sum;
}
}
}
return max;
}
2、动态规划解法:
class Solution {
public int maxSubArray(int[] nums) {// 动态规划法
int sum=nums[0];
int n=nums[0];
for(int i=1;i<nums.length;i++) {
if(n>0)n+=nums[i];
else n=nums[i];
if(sum<n)sum=n;
}
return sum;
}
}
上期推文: