@samzhang
2018-09-04T20:13:14.000000Z
字数 2337
阅读 1050
准备面试写的 sample exercise...
Given an one-dimensional array consisting of either negative or positive integers, you need to find a non-empty continuous subarray such its sum is maximal amony all subarrays. To simplify the task, only the sum itself is required.
We simply enumerate all the subarrays and take the maximum. The procedure is as follows:
max_sum = -inf
for i in 1..n
for j in i..n
if sum(a[i..j]) > max_sum:
max_sum = sum(a[i..j])
To get a more efficient algorithm, we have to utilise the underlying recursive structure of this problem.
Let denote the maximal sum of subarrays ending at the -th position. Why do we care about this? This is because that since the desired maximal subarray we are looking for must end somewhere between and (pretty trivial fact right?), its sum is just . If we can calculate all the fast, we are done. But how?
Firstly, let’s start from the easiest: . Since there is one and only one array ending at , is just .
Now assume we have found , how do we use this to calculate ?
Here we split it into two cases:
Easy! The sum is simply because is the unique subarray satisfies.
Then the array can be considered as a concatenation of a subarray ending at the th position and . Since is fixed, we only need to maximize the sum of the subarray ending at the th position. This is exactly what is for!. Therefore, the sum in this case is .
Hence, we have .
Therefore, we get the following recursive relation:
Suppose the array
Stage | current max | ||
---|---|---|---|
Therefore, the maximal subarray sum is .
Complete the following function:
def maxSum(a: [int], i):
···
Where is an array of integers and is the index. This function should return a pair of integers where the first entry is and the second is the current max
value as demonstrated in previous example. In this exercise you must write a recursive function to solve the problem i.e. no while
or for
loops in your program.
def maxSum(a: [int], i):
if i == 0:
return a[0], a[0]
else:
prevMax, curAns = maxSum(a, i - 1)
curMax = max(a[i], a[i] + prevMax)
return curMax, max(curMax, curAns)
print("Please inpunt an array of numbers:")
array = [int(i) for i in input().split()]
print("The maximal subarray sum is {}.".format(maxSum(array, len(array) - 1)[1]))