|
| 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 (47.75%) |
| 10 | + * Total Accepted: 1.3M |
| 11 | + * Total Submissions: 2.8M |
| 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 | + * |
| 18 | + * Example 1: |
| 19 | + * |
| 20 | + * |
| 21 | + * Input: nums = [-2,1,-3,4,-1,2,1,-5,4] |
| 22 | + * Output: 6 |
| 23 | + * Explanation: [4,-1,2,1] has the largest sum = 6. |
| 24 | + * |
| 25 | + * |
| 26 | + * Example 2: |
| 27 | + * |
| 28 | + * |
| 29 | + * Input: nums = [1] |
| 30 | + * Output: 1 |
| 31 | + * |
| 32 | + * |
| 33 | + * Example 3: |
| 34 | + * |
| 35 | + * |
| 36 | + * Input: nums = [5,4,-1,7,8] |
| 37 | + * Output: 23 |
| 38 | + * |
| 39 | + * |
| 40 | + * |
| 41 | + * Constraints: |
| 42 | + * |
| 43 | + * |
| 44 | + * 1 <= nums.length <= 3 * 10^4 |
| 45 | + * -10^5 <= nums[i] <= 10^5 |
| 46 | + * |
| 47 | + * |
| 48 | + * |
| 49 | + * Follow up: If you have figured out the O(n) solution, try coding another |
| 50 | + * solution using the divide and conquer approach, which is more subtle. |
| 51 | + */ |
| 52 | +class Solution { |
| 53 | + public int maxSubArray(int[] nums) { |
| 54 | + if (nums.length == 1) { |
| 55 | + return nums[0]; |
| 56 | + } |
| 57 | + int sum = nums[0]; |
| 58 | + int total = 0; |
| 59 | + for (int i = 1 ; i < nums.length; i++){ |
| 60 | + total = total + nums[i]; |
| 61 | + } |
| 62 | + |
| 63 | + Integer runningSum = sum; |
| 64 | + |
| 65 | + for (int i = 1 ; i < nums.length; i++) { |
| 66 | + if (sum + nums[i] < nums[i]) { |
| 67 | + sum = nums[i]; |
| 68 | + } else { |
| 69 | + sum += nums[i]; |
| 70 | + } |
| 71 | + if(sum > runningSum) { |
| 72 | + runningSum = sum; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + if (runningSum > total) { |
| 77 | + return runningSum; |
| 78 | + } |
| 79 | + |
| 80 | + return total; |
| 81 | + } |
| 82 | + |
| 83 | +} |
0 commit comments