欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python编写PAT 1007 Maximum Subsequence Sum

程序员文章站 2024-01-05 18:15:40
python编写PAT甲级 1007 Maximum Subsequence Sum wenzongxiao1996 2019.4.3 题目 Given a sequence of K integers { N ​1 ​​ , N ​2 ​​ , ..., N ​K ​​ }. A continuo ......

python编写pat甲级 1007 maximum subsequence sum

wenzongxiao1996
2019.4.3

题目

given a sequence of k integers { n
​1
​​ , n
​2
​​ , ..., n
​k
​​ }. a continuous subsequence is defined to be { n
​i
​​ , n
​i+1
​​ , ..., n
​j
​​ } where 1≤i≤j≤k. 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 (≤10000). 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

暴力解法(超时了)

def seq_sum(s):
    """求序列的所有元素之和"""
    result = 0
    for i in range(len(s)):
        result += s[i]
    return result

def main():
    n = int(input())
    seq = [int(i) for i in input().split()]
    max = -1
    pos_i = 0
    pos_j = n-1
    for i in range(n):
        for j in range(i,n):
            sum_temp = seq_sum(seq[i:j+1])
            if sum_temp > max:
                max = sum_temp
                pos_i = i
                pos_j = j
    if max < 0:
        print(0,seq[pos_i],seq[pos_j])
    else:
        print(max,seq[pos_i],seq[pos_j])

if __name__ == '__main__':
    main()

分治法

def division_solution(seq,left,right):
    if left == right: # 递归出口
        if seq[left] >= 0:
            return left,right,seq[left]
        else:
            return left,right,-1
    center = (left+right)//2 # 地板除

    # 从中间到左边的最大子串
    sum_left = 0
    max_sum_left = -1  # 一定要设为负数
    pos_left = left   # 要返回下标
    for i in range(left,center+1)[::-1]:  # 反向迭代
        sum_left += seq[i]
        if sum_left >= max_sum_left:
            max_sum_left = sum_left
            pos_left = i

    # 从中间到右边的最大子串
    sum_right = 0
    max_sum_right = -1  # 一定要设为负数
    pos_right = right  # 要返回下标
    for i in range(center+1,right+1):
        sum_right += seq[i]
        if sum_right > max_sum_right:
            max_sum_right = sum_right
            pos_right = i

    # 递归求解左右两个子问题
    i_left,j_left,max_left_sum = division_solution(seq,left,center)
    i_right,j_right,max_right_sum = division_solution(seq,center+1,right)

    if max(max_left_sum,max_right_sum,max_sum_left+max_sum_right) < 0:
        return left,right,-1
    else:
        if max(max_left_sum,max_right_sum,max_sum_left+max_sum_right) == max_left_sum:
            return i_left,j_left,max_left_sum
        elif max(max_left_sum,max_right_sum,max_sum_left+max_sum_right) == max_right_sum:
            return i_right,j_right,max_right_sum
        else:
            return pos_left,pos_right,max_sum_left+max_sum_right


def main():
    n = int(input())
    seq = [eval(i) for i in input().split()]
    i,j,sum_max = division_solution(seq,0,n-1)
    if sum_max < 0:
        print(0,seq[0],seq[-1])
    else:
        print(sum_max,seq[i],seq[j])

if __name__ == '__main__':
    main()

动态规划

def main():
    n = int(input())
    seq = [eval(i) for i in input().split()]
    sum_max = -1
    pos_i = 0
    pos_i_temp = 0 # 最大子序列的左下标不能随意更改,只有找到了更大的子串才能改,用这个变量先保存着当前寻找的子串的左下标
    pos_j = n-1
    sum_temp = 0
    for i in range(n):
        sum_temp += seq[i]
        if sum_temp > sum_max:
            sum_max = sum_temp
            pos_j = i
            pos_i = pos_i_temp
        elif sum_temp < 0 # 和小于0的子串不需要考虑
            sum_temp = 0
            pos_i_temp = i+1
    if sum_max < 0:
        print(0,seq[0],seq[-1])
    else:
        print(sum_max,seq[pos_i],seq[pos_j])

if __name__ == '__main__':
    main()

谢谢观看!敬请指正!
参考博客:
原题链接:

上一篇:

下一篇: