-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSubArray.java
More file actions
38 lines (35 loc) · 1.03 KB
/
MaxSubArray.java
File metadata and controls
38 lines (35 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.cier.solution.dp;
/**
* @program: Leetcode
* @description: 最大子序列和
* @author: liuenci
* @create: 2020-12-17 19:43
**/
public class MaxSubArray {
public static void main(String[] args) {
MaxSubArray maxSubArray = new MaxSubArray();
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int[] nums1 = {1};
System.out.println(maxSubArray.maxSubArray(nums));
}
public int maxSubArray(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0];
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]);
max = Math.max(max, dp[i]);
}
return max;
}
public int maxSubArray1(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0];
int max = dp[0];
for (int i = 1; i < dp.length; i++) {
dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]);
max = Math.max(dp[i], max);
}
return max;
}
}