-
Notifications
You must be signed in to change notification settings - Fork 639
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
字节二面&leetcode53:最大子序和 #94
Comments
解法:动态规划动态规划(Dynamic Programming,DP)是一种将复杂问题分解成小问题求解的策略,但与分治算法不同的是,分治算法要求各子问题是相互独立的,而动态规划各子问题是相互关联的。
我们使用动态规划求解问题时,需要遵循以下几个重要步骤:
第一步:定义子问题 动态规划是将整个数组归纳考虑,假设我们已经知道了以第 第二步:实现需要反复执行解决的子子问题部分 dp[n] = Math.max(dp[n−1]+nums[n], nums[n]) 第三步:识别并求解出边界条件 dp[0]=nums[0] 最后一步:把尾码翻译成代码,处理一些边界情况 因为我们在计算 代码实现(优化): let maxSubArray = function(nums) {
let max = nums[0], pre = 0
for(const num of nums) {
if(pre > 0) {
pre += num
} else {
pre = num
}
max = Math.max(max, pre)
}
return max
} 复杂度分析:
|
dpfunction longestSum(nums) {
const dp = [nums[0]];
let max = -Infinity;
for(let i=1; i<nums.length; i++) {
if(dp[i-1]>0) {
dp[i] = dp[i-1] + nums[i];
max = max > dp[i] ? max : dp[i];
} else {
dp[i] = nums[i];
max = max > dp[i] ? max : dp[i];
}
}
return max;
} dp[i]表示以nums[i]结尾的,最大的连续值。 |
var maxSubArray = function(nums) {
let max = nums[0], sum = 0;
for(item of nums) {
sum += item;
max = Math.max(max, sum);
sum = sum < 0 ? 0 : sum;
}
return max;
}; |
给定一个整数数组
nums
,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。示例:
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
附赠leetcode地址:leetcode
The text was updated successfully, but these errors were encountered: