From 4dfbf67583fb59a5de8338d589a46dad23665811 Mon Sep 17 00:00:00 2001 From: yuanguangxin <274841922@qq.com> Date: Mon, 3 Feb 2020 15:16:30 +0800 Subject: [PATCH] add q53 --- .idea/workspace.xml | 95 ++++++++++++++++++++++++---------------- src/q53/q1/Solution.java | 31 +++++++++++++ src/q53/q2/Solution.java | 24 ++++++++++ 3 files changed, 113 insertions(+), 37 deletions(-) create mode 100644 src/q53/q1/Solution.java create mode 100644 src/q53/q2/Solution.java diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 09733f1..b0a3f28 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,10 +2,9 @@ - - + + - - + + + - + + - - @@ -212,7 +224,8 @@ - + + 1580045439607 @@ -263,7 +276,14 @@ - @@ -277,69 +297,70 @@ - - + - - + + - - + + - - - + + + - - - + + + - - - + + + - - - + + + - + - + - + - + - + - + - + - + - + diff --git a/src/q53/q1/Solution.java b/src/q53/q1/Solution.java new file mode 100644 index 0000000..a818c11 --- /dev/null +++ b/src/q53/q1/Solution.java @@ -0,0 +1,31 @@ +package q53.q1; + +/** + * 贪心法 遍历一次 o(n) + */ +public class Solution { + public int maxSubArray(int[] nums) { + if (nums.length == 1) { + return nums[0]; + } + int sum = nums[0]; + int temp = sum; + for (int i = 1; i < nums.length; i++) { + temp = temp + nums[i]; + if (temp >= sum) { + sum = temp; + } else if (temp < 0) { + temp = 0; + } + if (nums[i] > sum) { + temp = nums[i]; + sum = nums[i]; + } + } + return sum; + } + + public static void main(String[] args) { + System.out.println(new Solution().maxSubArray(new int[]{-1, 1, 2, 1})); + } +} diff --git a/src/q53/q2/Solution.java b/src/q53/q2/Solution.java new file mode 100644 index 0000000..2af4b45 --- /dev/null +++ b/src/q53/q2/Solution.java @@ -0,0 +1,24 @@ +package q53.q2; + +/** + * 动态规划 dp[i]表示以nums[i]结尾的最大子序和 o(n) + */ +public class Solution { + public int maxSubArray(int[] nums) { + int[] dp = new int[nums.length]; + dp[0] = nums[0]; + + int rs = dp[0]; + + for (int i = 1; i < nums.length; i++) { + int temp = dp[i - 1] + nums[i]; + dp[i] = Math.max(nums[i],temp); + rs = Math.max(rs, dp[i]); + } + return rs; + } + + public static void main(String[] args) { + System.out.println(new Solution().maxSubArray(new int[]{-2})); + } +}