贪心法求最值
作者:互联网
个人解题思路,仅供参考
import java.util.Date; public class Test { /** * 给定一个数组arr,返回子数组的最大累加和 * 例如,arr = [1, -2, 3, 5, -2, 6, -1],所有子数组中,[3, 5, -2, 6]可以累加出最大的和12,所以返回12. * 题目保证没有全为负数的数据 * [要求] * 时间复杂度为O(n)O(n),空间复杂度为O(1)O(1) */ public static void main(String[] args) { int[] n = new int[]{1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1 , 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1 , 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1 , 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1 , 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1 , 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1 , 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1, 1, -2, 3, 5, -2, 6, -1}; System.out.println(new Date()); System.out.println(maxsumofSubarray(n)); System.out.println(new Date()); } /** * @param arr * @return */ public static int maxsumofSubarray(int[] arr) { int sum = 0; for (int i =0; i< arr.length; i++) { if ((sum + arr[i]) > sum) sum += arr[i]; } return sum; } }
执行结果:
标签:arr,int,sum,System,Date,法求,out,最值,贪心 来源: https://www.cnblogs.com/zhlii/p/14487436.html