程序员入门水平,贴出代码大家一起进步!
原题传送门
题目
Given a sequence of K integers { N1 , N2 , …, NK }. A continuous subsequence is defined to be { Ni
, Ni+1 , …, Nj } 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
思路||总结
- 开始使用暴力解决,最后一个测试点超时,后来看别人说可以一次循环解决,想了半天还是有问题,最后参考了柳神的博客。
AC代码
def main():
k = int(input().strip())
nums = input().strip().split()
for i in range(k):
nums[i] = int(nums[i])
sum_num = -1
left_idx = 0
right_idx = k - 1
temp_idx = 0
temp_sum = 0
for i in range(k):
temp_sum = temp_sum + nums[i]
if temp_sum < 0:
temp_sum = 0
temp_idx = i + 1
elif temp_sum > sum_num:
sum_num = temp_sum
left_idx = temp_idx
right_idx = i
if sum_num < 0:
sum_num = 0
print(sum_num, nums[left_idx], nums[right_idx], end='')
main()
A暴力代码(最后一个测试点超时)
def main():
k = int(input().strip())
nums = input().strip().split()
for i in range(k):
nums[i] = int(nums[i])
max_num = [-1, 0, k - 1]
for sum_len in range(1, k + 1):
for i in range(k + 1 - sum_len):
if nums[i + sum_len - 1] < 0:
continue
#print(nums[i + sum_len - 1])
if sum(nums[i:i + sum_len]) > max_num[0]:
max_num[0] = sum(nums[i:i + sum_len])
max_num[1] = i
max_num[2] = i + sum_len - 1
elif sum(nums[i:i + sum_len]) == max_num[0] and i < max_num[1]:
max_num[1] = i
max_num[2] = i + sum_len - 1
if max_num[0] < 0:
print(0, nums[0], nums[len(nums) - 1], end='')
else:
print(max_num[0], nums[max_num[1]], nums[max_num[2]], end='')
main()