4.1 最大子数组问题
Posted CLRS solutions
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了4.1 最大子数组问题相关的知识,希望对你有一定的参考价值。
-
位于子数组 -
位于子数组 -
跨越了中点
FIND-MAX-CROSSING-SUBARRAY
(A,low,mid,high)
left_sum = -INF
sum = 0
for i = mid downto low
sum = sum + A[i]
if sum > left_sum
left_sum = sum
max_left = i
right_sum = -INF
sum = 0
for j = mid+1 to high
sum = sum+A[j]
if sum > right_sum
right_sum = sum
max_right = j
return(max_left,max_right
,left_sum+right_sum)
FIND-MAXIMUM-SUBARRAY
(A,low,high)
if high == low //base case
return(low,high,A[low])
else
mid = (low+high)/2
(left_low,left_high,left_sum) =
FIND-MAXIMUM-SUBARRAY
(A,low,mid)
(right_low,right_high,right_sum) =
FIND-MAXIMUM-SUBARRAY
(A,mid+1,high)
(cross_low,cross_high,cross_sum) =
FIND-MAX-CROSSING-SUBARRAY
(A,low,mid,high)
if left_sum >= right_sum and
left_sum >= cross_sum
return (left_low,left_high,left_sum)
else if right_sum >= left_sum and
right_sum >= cross_sum
return (right_low,right_high
,right_sum)
else return(cross_low,cross_high
,cross_sum)
Kadane's algorithm
int max_so_far = a[0];
int max_ending_here = a[0];
for (int i = 1; i < size; i++)
{
max_ending_here = Math.max(a[i], max_ending_here+a[i]);
max_so_far = Math.max(max_so_far, max_ending_here);
}
return max_so_far;
以上是关于4.1 最大子数组问题的主要内容,如果未能解决你的问题,请参考以下文章
文心一言 VS 讯飞星火 VS chatgpt (18)-- 算法导论4.1 5题
NC41 最长无重复子数组/NC133链表的奇偶重排/NC116把数字翻译成字符串/NC135 股票交易的最大收益/NC126换钱的最少货币数/NC45实现二叉树先序,中序和后序遍历(递归)(代码片段