题目:HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。你会不会被他忽悠住?(子向量的长度至少是1)
package test; import org.junit.Test; public class FindGreatestSumOfSubArray { int maxNum = Integer.MIN_VALUE; /** * 基于递归写法,时间复杂度o(n) * * @param i * @param a * @return */ public int FindGreatestSumOfSubArray(int i, int[] a) { if (i == 0) return a[i]; else { int tmp = FindGreatestSumOfSubArray(i - 1, a) + a[i]; if (tmp <= 0) { return a[i]; } if (tmp <a[i]){ tmp = a[i]; } if (tmp > maxNum) { maxNum = tmp; } return tmp; } } /** * 递归方法的调用 * * @param i * @param a * @return */ public int FindGreatestSumOfSubArrayRecru(int[] a) { int result = FindGreatestSumOfSubArray(a.length - 1, a); if (result < maxNum) return maxNum; else return result; } /** * 暴力搜索的方法,时间复杂度o(n^2) * @param a * @return */ public int FindGreatestSumOfSubArrayViolent(int[] a) { // 暴力搜索 int max = 0; for (int i = 0; i < a.length; i++) { int result = a[i]; for (int j = i + 1; j < a.length; j++) { result += a[j]; if (result > max) { max = result; } } } return max; } /** * 动态规划写法,时间复杂度o(n),时间复杂度O(1) * @param a * @return */ public int FindGreatestSumOfSubArrayDP(int[] a) { //基于数组特性,也叫动态规划 if (a == null || a.length == 0)return 0; int max = Integer.MIN_VALUE; int result = 0; for(int i=0;i<a.length;i++){ /* if (result <= 0){ result = a[i]; }else{ result += a[i]; } if (result > max){ max = result; }*/ //if,else的另一种写法: result = (result < 0)?a[i]:a[i]+result; max = (result > max)?result:max; } return max; } @Test public void test() { int[] a = { 1, -2, 3, 10, -4, 7, 2, -5 }; int result1 = FindGreatestSumOfSubArrayRecru(a); System.out.println(result1); //18 int result2 = FindGreatestSumOfSubArrayDP(a); System.out.println(result2);//18 int result3 = FindGreatestSumOfSubArrayViolent(a); System.out.println(result3);//18 } }
时间: 2024-10-04 03:12:26