PAT A1007 Maximum Subsequence Sum Go语言题解及注意事项
1007 Maximum Subsequence Sum (25分)
Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.
Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.
Input Specification:
Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (≤). The second line contains K numbers, separated by a space.
Output Specification:
For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.
Sample Input:
10
-10 1 2 3 4 -5 -23 3 7 -21
Sample Output:
10 1 4
思路
动态规划的入门,本题的难点在于如何定义状态dp[i],更新dp的过程中记录最大和max和最大和子序列的最后一个下标index
状态定义: 设动态规划列表 dp ,dp[i]代表以元素 nums[i]为结尾的连续子数组最大和。
转移方程: 当 dp[i - 1] > 0 时:dp[i] = dp[i-1] + nums[i] ; 当dp[i−1] ≤ 0时 ,说明 dp[i - 1]+nums[i]还不如nums[i]自己大,所以直接舍弃前边,令dp[i]=nums[i]
- 当 dp[i - 1] > 0 时:dp[i] = dp[i-1] + nums[i] ;
- 当 dp[i - 1] ≤0 时:dp[i] = nums[i]
初始状态: dp[0] = nums[0],即以 nums[0] 结尾的连续子数组最大和为 nums[0] 。
注意事项
-
状态转移方程不要错,当dp[i-1]<0的时候直接舍弃前边的,令dp[i]=nums[i]
-
不管是任何一种情况更新dp之后dp[i]都要和max比较,即DP放在整个循环的下边而不是if或者else的括号里
- 在dp[i]和max比较的时候,一定是dp[i]大于max才更新index,这样可以保证出现相同maxSum时输出的是下标最小的那组
- 题目最后一句:If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.
- 当数组只有负数和0的时候,输出“0 0 0”
Solution(Golang)
package main
import "fmt"
var k int
func main() {
fmt.Scan(&k)
nums := make([]int, k)
for i := 0; i < k; i++ {
fmt.Scan(&nums[i])
}
dp := make([]int, k)
dp[0] = nums[0]
max := nums[0]
index := 0
for i := 1; i < k; i++ {
if dp[i-1] > 0 {
dp[i] = dp[i-1] + nums[i]
} else {
dp[i] = nums[i]
}
if dp[i] > max {
max = dp[i]
index = i
}
}
if max < 0 {
fmt.Println(0, nums[0], nums[k-1])
} else {
fmt.Print(max)
for j := index; j >= 0; j-- {
max = max - nums[j]
if max == 0 {
fmt.Printf(" %d ", nums[j])
break
}
}
fmt.Print(nums[index])
}
}

浙公网安备 33010602011771号