lintcode 最大子数组(Maximum Subarray )(Java)
2017-07-12 15:11
281 查看
题目
给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。注意事项
子数组最少包含一个数
样例
给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6分析
思路一:个人思路进行两次循环,遍历所有可能的情况,找到最大的子数组,时间复杂度为O(n^2);
思路二:动态规划(查资料)
对于任意一个子数组和,如果大于0,那么它再添加一个数,他的贡献是正值,如果子数组和小于0,再添加一个数,它的贡献则为负值,这时候不如将当前子数组舍掉,新数成为一个新数组。
代码
//思路一 public class Solution { /** * @param nums: A list of integers * @return: A integer indicate the sum of max subarray */ public int maxSubArray(int[] nums) { // write your code if (nums.length == 1) return nums[0]; int max = nums[0]; for (int i = 0; i < nums.length; i++){ int temp = nums[i]; for (int j = i+1; j < nums.length; j++){ temp += nums[j]; if (temp > max){ max = temp; } } } return max; } }
//思路二 public int maxSubArray(int[] nums) { // write your code int max = Integer.MIN_VALUE; int sum = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++){ sum = sum<0 ? nums[i] : nums[i]+sum; if (sum>max){ max = sum; } } return max; }
d3ed
相关文章推荐
- Java 中一个int型数组的求最大值最小值
- 求连续子数组的最大和O(n)解法之思路与Java实现
- JAVA冒泡排序/JAVA冒泡排序再找出给定数据中的最大值最小值/JAVA数组排序
- [原]Java面试题-输入一个整型数组,找出最大值、最小值,并交换。
- java 数组求最大值
- C/C++与Java多维数组,遍历与最大值获取方法!
- 子数组求最大和-算法-java
- java数组(最大、小值,排序)
- [java实现]找一个数组的最大和的连续子数组(时间复杂度 O(n))
- java二维数组求每行最大值,每列最小值,及输出数组主对角线上的元素
- Java有N个数字的int类型数组,如何获取数量最多并且数字最大的数以及数量
- Java 数组中最大递增子数组
- java代码测试集合,数组等最大存储大小
- 一维数组及子数组最大和问题Java实现
- 数组问题之一维最大字段和问题<Java实现>
- java数组中求最大值
- java 计算数组中的最大,次大,最小,次小的数
- 2、 java 已知一个int数组, 编程从数组中获取最大数.
- Java 动态规划来求数组连续最大的和
- java面向对象之数组中最大数