京都大学 情報学研究科 知能情報学専攻 2022年2月実施 基礎科目 F2-1
Author
祭音Myyura (co-authored with GPT 5.6 SOL)
Description
Q.1
The following function func returns the largest value of
with , given an integer array of size .
int func(int A[], int n) {
int d = 0;
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
if (A[j] - A[i] > d)
d = A[j] - A[i];
return d;
}
(1) Describe the time complexity of the algorithm with reasons.
(2) If an algorithm with better time complexity exists, give its code and time complexity.
Q.2
A maximum value contiguous subsequence (MVCS) is a contiguous subsequence of
an integer sequence whose element sum is maximum among all contiguous
subsequences. For example, an MVCS of
[-5, 3, 7, -4] is [3, 7], with sum , and an MVCS of
[-5, 3, 7, -4, 5, 3, -20] is [3, 7, -4, 5, 3], with sum .
Give an efficient algorithm that computes the sum of an MVCS of a length- sequence , and state its time complexity.
题目描述
- 题给双重循环函数
func,其返回整数数组 中 时 的最大值。- 说明该算法的时间复杂度;
- 若有更快算法,写出代码及其时间复杂度。
- 最大值连续子序列(MVCS)是元素和在所有连续子序列中最大的连续子序列。 给出计算长度为 的整数序列 的 MVCS 元素和的高效算法,并回答时间复杂度。
Kai
Q.1
(1)
For each , the inner loop executes times. Hence the total number of iterations is
Each iteration takes constant time, so the running time is
(2)
Maintain the minimum value seen at an index not exceeding the current .
int func_linear(int A[], int n) {
int d = 0;
int min_value = A[0];
for (int j = 0; j < n; j++) {
if (A[j] - min_value > d)
d = A[j] - min_value;
if (A[j] < min_value)
min_value = A[j];
}
return d;
}
Immediately before the first comparison at iteration , min_value is the
minimum of the preceding values (with A[0] used when ). If A[j] is a
new minimum, choosing gives , which is already covered by
d = 0. After the second comparison, min_value equals
. Thus the algorithm considers the best valid
for every . It uses
Q.2
For a nonempty MVCS, Kadane's algorithm is
ending = A[0]
best = A[0]
for i = 1 to n - 1:
ending = max(A[i], ending + A[i])
best = max(best, ending)
return best
After processing , ending is the largest sum of a contiguous
subsequence ending exactly at , while best is the largest sum seen at any
ending position. Thus the returned value is the MVCS sum.
The loop examines each element once, so the complexity is