原题链接:https://leetcode-cn.com/problems/maximum-subarray/
题目描述
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入:
[-2,1,-3,4,-1,2,1,-5,4]
输出:
6
解释:
连续子数组 [4,-1,2,1] 的和最大,为 6。
暴力破解法,列举出所有可能:
例:数组 [-2,1,-3,4,-1,2,1,-5,4]
排列出组合:[-2]
[-2,1]
[-2,1,-3]
…
[1]
[1,-3]
…
代码示例:
import java.util.Scanner;
public class 最大子序和 {
public static void main(String[] args) {
// 输入问题
Scanner sc = new Scanner(System.in);
// 输入数组的长度
int n = sc.nextInt();
// 创建数组输入数据
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
// 输出最大子序和
System.out.println(maxSubArray(nums));
}
//解决问题
public static int maxSubArray(int[] nums) {
// 最大值
int max = nums[0];
// 遍历数组中所有数据
for (int i = 0; i < nums.length; i++) {
int temp = nums[i];
// 比较所有连续组合中那个值最大
max = max > temp ? max:temp;
for (int j = i+1; j < nums.length; j++) {
temp += nums[j];
max = max > temp ? max:temp;
}
// System.out.println(max+" "+temp);
}
return max;
}
}