-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumSubarray.java
More file actions
32 lines (28 loc) · 894 Bytes
/
MaximumSubarray.java
File metadata and controls
32 lines (28 loc) · 894 Bytes
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
package leetcode.array;
/**
* @Author: ChangXuan
* @Decription: Given an integer array nums, find the contiguous subarray (containing at least one number)
* which has the largest sum and return its sum. https://leetcode-cn.com/problems/maximum-subarray/
* @Date: 17:39 2020/6/26
**/
public class MaximumSubarray {
public static void main(String[] args) {
int[] test = {-2,1,-3,4,-1,2,1,-5,4};
System.out.println(maxSubArray(test));
}
/**
* 普通方法
* @param nums 数据
* @return 最大值
*/
public static int maxSubArray(int[] nums) {
int currentSum = 0;
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++){
currentSum += nums[i];
maxSum = Math.max(currentSum, maxSum);
currentSum = Math.max(currentSum, 0);
}
return maxSum;
}
}