京都大学 情報学研究科 通信情報システム専攻 2017年8月実施 専門基礎B [B-7]
Author
祭音Myyura
Description
最大連続部分和問題とは、与えられた
と記したとき、
(1) 以下の表は
(2) 任意の整数
(3) 分割統治法及び (2) のアルゴリズムを用いて、最大連続部分和問題を
(4) 任意の
が成立することを示せ。この関係式に基づき、最大連続部分和問題を
Kai
(1)
(2)
The idea is simple, find the maximum sum starting from mid point (
def max_crossing_sum(A, s, t, k):
# 1. mid to left
current_sum = 0
max_left_sum = -10000
for i in range(k, s - 1, -1): # for i = k to s:
current_sum += A[i]
if current_sum > max_left_sum:
max_left_sum = current_sum
# 2. mid to right
current_sum = 0
max_right_sum = -10000
for i in range(k, t + 1): # for i = k to t:
current_sum += A[i]
if current_sum > max_right_sum:
max_right_sum = current_sum
return max(max_left_sum + max_right_sum - A[k], max_left_sum, max_right_sum)
Obviously, the time complexity
(3)
The algorithm can be described as follows:
- Divide the given array in two halves
- Return the maximum of following three
- Maximum subarray sum in left half (Make a recursive call)
- Maximum subarray sum in right half (Make a recursive call)
- Maximum subarray sum such that the subarray crosses the midpoint (Algorithm in (2))
def max_subarray_sum(A, s, t):
if s > t:
return -10000
if s == t:
return A[s]
k = (s + t) // 2
return max(max_subarray_sum(A, s, k - 1),
max_subarray_sum(A, k + 1, t),
max_crossing_sum(A, s, t, k))
The time complexity
(4)
The calculation of
If the sum of maximum subarray ending at
If the sum of maximum subarray ending at
Combining the two cases we have
and the maixmum subarray sum
The algorithm is described as follows:
def max_subarray_sum(A, n):
dp = [0] * n
dp[0] = A[0]
ans = dp[0]
for i in range(1, n):
dp[i] = max(A[i], A[i] + dp[i-1])
ans = max(ans, dp[i])
return ans
Obviously, the time complexity is