题目:给定一个无序数组arr, 其中元素可正、可负、可0。给定一个整数k,求arr所有子数组中累加和为k的最长子数组长度。
分析:先采用快速排序算法对数组进行排序,再进行判断每个子数组的长度,取最长得长度。
code:
#[n,k] = list(map(int,input().split()))
#inp = list(map(int,input().split()))
def quick_sort(lists, left, right):
if left > right:
return lists
key = lists[left]
low = left
high = right
while left < right:
if left < right and lists[right] >= key:
right -= 1
lists[left] = lists[right]
if left < right and lists[left] <= key:
left += 1
lists[right] = lists[left]
lists[right] = key
quick_sort(lists, low, left - 1)
quick_sort(lists, left + 1, high)
return lists
[n, k] = 5, 3
inp = [1, -2, 1, 1, 1]#[1, 2, 1, 1, 1]
inp = quick_sort(inp, 0, len(inp) - 1)
maxLen = 0
Sum = 0
l = 0
for i in range(len(inp)):
Sum += inp[i]
if Sum > k:
Sum -= inp[l]
l += 1
if i - l + 1 > maxLen:
maxLen = i - l + 1
print(maxLen)
程序运行结果为:
5
网友评论