|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
https://www.codewars.com/kata/54 ... 000d6c/train/python
The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:
- max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
- # should be 6: [4, -1, 2, 1]
复制代码
Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.
Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.
我的代码:
- def max_sequence(arr):
- maxsum = 0
- for i in range(len(arr) - 4):
- i = arr[i]
- j = arr[i + 1]
- k = arr[i + 2]
- l = arr[i + 3]
- if (i + j + k + l) > maxsum:
- maxsum = i + j + k + l
- return maxsum
复制代码
评测结果:
Fixed tests
Should work on an empty array
Should obtain correct maximum subarray sum in the array from the kata description example
2 should equal 6
Completed in 0.05ms
Should obtain correct maximum subarray sum in an example with negative numbers
Should obtain correct maximum subarray sum in a complex example
Unexpected exception raised
Traceback (most recent call last):
File "/workspace/default/.venv/lib/python3.11/site-packages/codewars_test/test_framework.py", line 112, in wrapper
func()
File "/workspace/default/tests.py", line 26, in test_complex_array
test.assert_equals(max_sequence([7, 4, 11, -11, 39, 36, 10, -6, 37, -10, -32, 44, -26, -34, 43, 43]), 155)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/workspace/default/solution.py", line 5, in max_sequence
j = arr[i + 1]
~~~^^^^^^^
IndexError: list index out of range
???
你的问题在于你在遍历数组时,没有正确地处理索引和其值。在这一行 i = arr[ i] ,你把数组的值赋给了 i ,之后你就无法用 i 作为正确的索引值了,所以 j = arr[i + 1] 将会引发 "list index out of range" 这样的错误。
你可以使用一个叫做Kadane算法的更有效的算法来解决这个问题。该算法的基本思想是在每个步骤中保留最大的(正的)子序列和。当这个总和变为负数时,我们则将其重置为0。
以下是实现该算法的代码:
- def max_sequence(arr):
- max_ending_here = max_ending_so_far = 0
- for num in arr:
- max_ending_here = max(0, max_ending_here + num)
- max_ending_so_far = max(max_ending_so_far, max_ending_here)
- return max_ending_so_far
复制代码
在这段代码中, max_ending_here 是当前子序列的最大和, max_ending_so_far 是到目前为止找到的最大子序列的和。
代码的工作原理是:遍历数组的每个元素,并在 max_ending_here 中保持一个正在运行的总和。如果 max_ending_here 变为负数,我们就把它重置为0。同时,我们用 max_ending_so_far 记录找到的最大和。
这种方法的优点是,我们只需要遍历一次数组,所以时间复杂度是 O(n),n 为数组的长度。这种方法比你的原始方法更高效,因为你的方法需要多次遍历数组(每次遍历四个连续的元素),其时间复杂度是 O(n^4)。
你的方法也有一个限制,即只能找到长度为4的子序列的最大和。而Kadane算法能找到任何长度的子序列的最大和。
|
|