最大子数组之和对应的子数组

xiaoxiao2021-03-01  11

给定一个整数数组(包含正负数),找到一个具有最大和的子数组,返回其最大的子数组 public static List<Integer> subArraySumItem(int[] params) { int currentSum = 0; int maxSum = 0; int curStart = 0; int start = 0; int end = 0; for (int i = 0; i < params.length; i++) { currentSum += params[i]; if(currentSum > 0) { if (currentSum > maxSum) { maxSum = currentSum; start = curStart ; end = i; } }else{ currentSum = 0; curStart = i ; } } List<Integer> list = new ArrayList<Integer>(); for (int i = start+1; i <=end ; i++) { list.add(params[i]); } return list; }

 

/** * 给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。 * 样例 * 给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6 * * @param args */ public static void main(String[] args) { int[] arrays = new int[]{-2, 2, -3, 4, -1, 2, 1, -5, 3}; List<Integer> list = subArraySumItem(arrays); System.out.println("list=" + JsonUtil.toJson(list)); }
转载请注明原文地址: https://www.6miu.com/read-3650010.html

最新回复(0)