LeetCode:53. Maximum Subarray(找出陣列中和最大的陣列)
阿新 • • 發佈:2018-12-10
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.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
方法1:這種方式比較好理解,也是我認為效率最高的演算法
package leetcode; import org.junit.Test; /** * @author zhangyu * @version V1.0 * @ClassName: MaximumSubarray * @Description: * @date 2018/12/6 9:41 **/ public class MaximumSubarray2 { @Test public void fun() { int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; int maxNum = maximumSubarray(nums); System.out.println(maxNum); } //這種比較直接,又通俗易懂的方式 private int maximumSubarray(int[] nums) { int max = nums[0], sum = 0; for (int i = 0; i < nums.length; i++) { if (sum < 0) { sum = nums[i]; } else { sum += nums[i]; } if (sum > max) { max = sum; } } return max; } }
時間複雜度:O(n)
空間複雜度:O(1)
方法2:利用動態規劃,最主要是狀態轉移方程
package leetcode; import org.junit.Test; /** * @author zhangyu * @version V1.0 * @ClassName: MaximumSubarray * @Description: 這種是採用動態規劃的方式進行求解 * @date 2018/12/6 9:41 **/ public class MaximumSubarray3 { @Test public void fun() { int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; int maxNum = maximumSubarray(nums); System.out.println(maxNum); } private int maximumSubarray(int[] nums) { // 如果陣列為空或者長度為0,直接返回0 if (nums == null || nums.length == 0) { return 0; } // 定義最大值為陣列開始的數 int result = nums[0]; int sum = nums[0]; for (int i = 1; i < nums.length; ++i) { // 主要是要想明白這個動態規劃的狀態轉換方程 sum = Math.max(sum + nums[i], nums[i]); result = Math.max(result, sum); } // 最後返回最大的那個數 return result; } }
時間複雜度:O(n)
空間複雜度:O(n)