|
1 |
| -/** |
2 |
| -Find the contiguous subarray within an array (containing at least one number) which has the largest sum. |
3 |
| -For example, given the array [-2,1,-3,4,-1,2,1,-5,4], |
4 |
| -the contiguous subarray [4,-1,2,1] has the largest sum = 6. |
5 |
| -**/ |
6 |
| - |
7 |
| -//Java solution: |
8 |
| - |
9 |
| -public class Solution { |
| 1 | +/* |
| 2 | + * @lc app=leetcode id=53 lang=java |
| 3 | + * |
| 4 | + * [53] Maximum Subarray |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/maximum-subarray/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Easy (42.32%) |
| 10 | + * Total Accepted: 440.3K |
| 11 | + * Total Submissions: 1M |
| 12 | + * Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]' |
| 13 | + * |
| 14 | + * Given an integer array nums, find the contiguous subarray (containing at |
| 15 | + * least one number) which has the largest sum and return its sum. |
| 16 | + * |
| 17 | + * Example: |
| 18 | + * Input: [-2,1,-3,4,-1,2,1,-5,4], |
| 19 | + * Output: 6 |
| 20 | + * Explanation: [4,-1,2,1] has the largest sum = 6. |
| 21 | + * |
| 22 | + * Follow up: |
| 23 | + * If you have figured out the O(n) solution, try coding another solution using |
| 24 | + * the divide and conquer approach, which is more subtle. |
| 25 | + * |
| 26 | + */ |
| 27 | + |
| 28 | +class Solution { |
10 | 29 | public int maxSubArray(int[] nums) {
|
11 |
| - if(nums == null || nums.length == 0){ |
| 30 | + if (nums.length == 0) { |
12 | 31 | return 0;
|
13 | 32 | }
|
14 | 33 |
|
15 |
| - int sum; |
16 |
| - int max; |
17 |
| - int result = Integer.MIN_VALUE; |
18 |
| - |
19 |
| - for(int i = 0; i < nums.length; i++){ |
20 |
| - sum = 0; |
21 |
| - max = Integer.MIN_VALUE; |
22 |
| - |
23 |
| - for(int j = i; j < nums.length; j++){ |
24 |
| - sum = sum + nums[j]; |
25 |
| - max = Math.max(sum, max); |
26 |
| - } |
27 |
| - result = Math.max(result, max); |
28 |
| - //sum = 0; |
29 |
| - //max = Integer.MIN_VALUE; |
30 |
| - } |
31 |
| - |
32 |
| - return result; |
33 |
| - } |
34 |
| -} |
| 34 | + int newsum = nums[0]; |
| 35 | + int max = nums[0]; |
35 | 36 |
|
36 |
| - |
37 |
| -/* |
38 |
| -public class Solution { |
39 |
| - public int maxSubArray(int[] A) { |
40 |
| - if (A == null || A.length == 0){ |
41 |
| - return 0; |
| 37 | + for(int i = 1; i < nums.length; i++) { |
| 38 | + newsum = Math.max(newsum + nums[i], nums[i]); |
| 39 | + max = Math.max(max, newsum); |
42 | 40 | }
|
43 | 41 |
|
44 |
| - int max = Integer.MIN_VALUE; |
45 |
| - int sum = 0; |
46 |
| - |
47 |
| - for (int i = 0; i < A.length; i++) { |
48 |
| - sum += A[i]; |
49 |
| - max = Math.max(max, sum); |
50 |
| - sum = Math.max(sum, 0); |
51 |
| - } |
52 |
| - |
53 | 42 | return max;
|
54 | 43 | }
|
55 | 44 | }
|
56 |
| -*/ |
57 |
| - |
0 commit comments