# Find Maximum Subarrays using Java

## The problem

Given an integer array `nums`, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

```Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.```

## The code

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```// This method takes an array of `ints` and returns an `int`
public int maxSubArray(int[] nums) {
// Set some `max` variables,
// ..firstly the minimum `Integer` value
// ..secondly `0`
int max = Integer.MIN_VALUE;
int iMax = 0;

// Loop through all input `nums`
for(int num : nums) {
// increment the `iMax` each loop
iMax = iMax + num;
// check if `num` is bigger than `iMax`
if(iMax < num) {
// set `iMax` to the `num`
iMax = num;
}
// set the `max` to the max of both our variables
max = Math.max(max,iMax);
}
// return the `max`
return max;
}
```Code language: Java (java)```
Subscribe
Notify of