1 暴力解
时间复杂度:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public int maxSubArray(int[] nums) { int max = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++) { for (int j = i; j < nums.length; j++) { int sum = 0; for (int k = i; k <= j; k++) { sum += nums[k]; } max = Math.max(max, sum); } } return max; } }
|
2 改进的暴力解
时间复杂度:
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution { public int maxSubArray(int[] nums) { int max = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++) { int sum = 0; for (int j = i; j < nums.length; j++) { sum += nums[j]; max = Math.max(max, sum); } } return max; } }
|
3 分治
时间复杂度:
4 贪心
时间复杂度:
1 2 3 4 5 6 7 8 9 10 11 12
| class Solution { public int maxSubArray(int[] nums) { int max = Integer.MIN_VALUE; int sum = 0; for (int i = 0; i < nums.length; i++) { if (sum < 0) sum = nums[i]; else sum += nums[i]; max = Math.max(max, sum); } return max; } }
|
5 动态规划
时间复杂度:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public int maxSubArray(int[] nums) { int max = Integer.MIN_VALUE; int[] dp = new int[nums.length]; for (int i = 0; i < nums.length; i++) { if (i == 0 || dp[i - 1] < 0) { dp[i] = nums[i]; } else { dp[i] = nums[i] + dp[i - 1]; } max = Math.max(max, dp[i]); } return max; } }
|
附录
安利一个算法学习网站:https://algo.itcharge.cn/