题目描述
The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:
Max.sequence(new int[]{-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.
***
###参考代码
>```java
>public class Max {
public static int sequence(int[] arr) {
int max_ending_here = 0, max_so_far = 0;
for (int v : arr) {
max_ending_here = Math.max(0, max_ending_here + v);
max_so_far = Math.max(max_so_far, max_ending_here);
}
return max_so_far;
}
}
https://www.codewars.com/kata/maximum-subarray-sum/solutions/java
Author: mortonfox
解题思路
要点是若一段子数组arr[i]
-arr[j]
之和为负数,则以这段数组的下一个元素arr[j + 1]
为终点的最大子数组之和必然为arr[j + 1]
本身
用一个for语句遍历数组arr
,指针为i
,每次循环更新两个变量max_ending_here
和max_so_far
变量max_ending_here
是以arr[i]
为结尾的最大子数组之和。拿题目中的例子来说,假设指针i
为1
,则以arr[1]
为结尾的最大子数组之和是1
(即arr[1]
自己)。当指针i
为5
的时候,最大子数组之和则为5
(即arr[3]
+arr[4]
+arr[5]
)
变量max_so_far
用来储存问题的答案,即到目前为止最大的子数组之和
每次循环,先将max_ending_here
加上arr[i]
,然后判断是否小于0,若小于零则将其归零。然后再比较max_ending_here
和max_so_far
,把最大值赋值给max_so_far
杂谈
看到这个题目第一反应就是动规,因为长的跟有向图求最短路径好像啊。去看了些关于贪心和DP的算法,但还是找不到思路。主要没想通问题的状态是怎样的。后来拖太长时间了干脆暴力膜试了一次,居然过了(吐槽一下出题人也太懒了吧总共就三个test)。这个参考代码是pass了以后看到的其他人的代码,思路看一遍就能懂但是做题的时候就是想不出来就很气o_o
还是得多刷题呀(扶额)
References
https://www.codewars.com/kata/maximum-subarray-sum/solutions/java