[关闭]
@samzhang 2018-09-04T20:13:14.000000Z 字数 2337 阅读 1067

准备面试写的 sample exercise...

Maximal Subarray Problem

Problem Description:

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.

Naive Solution in :

We simply enumerate all the subarrays and take the maximum. The procedure is as follows:

  1. max_sum = -inf
  2. for i in 1..n
  3. for j in i..n
  4. if sum(a[i..j]) > max_sum:
  5. max_sum = sum(a[i..j])

Smarter Recursive Solution in :

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:

Case 1: The length of the maximal subarray is :

Easy! The sum is simply because is the unique subarray satisfies.

Case 2: The length of the maximal subarray is greater or equal to :

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:

Example

Suppose the array

Stage current max

Therefore, the maximal subarray sum is .

Task

Complete the following function:

  1. def maxSum(a: [int], i):
  2. ···

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.

Solution

  1. def maxSum(a: [int], i):
  2. if i == 0:
  3. return a[0], a[0]
  4. else:
  5. prevMax, curAns = maxSum(a, i - 1)
  6. curMax = max(a[i], a[i] + prevMax)
  7. return curMax, max(curMax, curAns)
  8. print("Please inpunt an array of numbers:")
  9. array = [int(i) for i in input().split()]
  10. print("The maximal subarray sum is {}.".format(maxSum(array, len(array) - 1)[1]))
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注