leetcode 53. 53. 最大子数组和(超时)
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
package com.wyl.leetcode;
|
||||
|
||||
/**
|
||||
* 53.给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
|
||||
* <p>
|
||||
* 子数组
|
||||
* 是数组中的一个连续部分。
|
||||
* <p>
|
||||
* 示例 1:
|
||||
* <p>
|
||||
* 输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
|
||||
* 输出:6
|
||||
* 解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
|
||||
* 示例 2:
|
||||
* <p>
|
||||
* 输入:nums = [1]
|
||||
* 输出:1
|
||||
* 示例 3:
|
||||
* <p>
|
||||
* 输入:nums = [5,4,-1,7,8]
|
||||
* 输出:23
|
||||
*/
|
||||
public class MaxSubArray {
|
||||
/**
|
||||
* 超时
|
||||
*/
|
||||
public static int maxSubArray(int[] nums) {
|
||||
int max = Integer.MIN_VALUE;
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
int value = nums[i];
|
||||
max = Math.max(value, max);
|
||||
for (int i1 = i + 1; i1 < nums.length; i1++) {
|
||||
value = value + nums[i1];
|
||||
max = Math.max(value, max);
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(maxSubArray(new int[]{-1, -2}));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user