规范格式

This commit is contained in:
YDZ
2020-08-07 15:50:06 +08:00
parent 854a339abc
commit 4e11f4028a
1438 changed files with 907 additions and 924 deletions

View File

@ -0,0 +1,48 @@
package leetcode
// 解法一 DP
func maxSubArray(nums []int) int {
if len(nums) == 0 {
return 0
}
if len(nums) == 1 {
return nums[0]
}
dp, res := make([]int, len(nums)), nums[0]
dp[0] = nums[0]
for i := 1; i < len(nums); i++ {
if dp[i-1] > 0 {
dp[i] = nums[i] + dp[i-1]
} else {
dp[i] = nums[i]
}
res = max(res, dp[i])
}
return res
}
// 解法二 模拟
func maxSubArray1(nums []int) int {
if len(nums) == 1 {
return nums[0]
}
maxSum, res, p := nums[0], 0, 0
for p < len(nums) {
res += nums[p]
if res > maxSum {
maxSum = res
}
if res < 0 {
res = 0
}
p++
}
return maxSum
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}

View File

@ -0,0 +1,56 @@
package leetcode
import (
"fmt"
"testing"
)
type question53 struct {
para53
ans53
}
// para 是参数
// one 代表第一个参数
type para53 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans53 struct {
one int
}
func Test_Problem53(t *testing.T) {
qs := []question53{
question53{
para53{[]int{-2, 1, -3, 4, -1, 2, 1, -5, 4}},
ans53{6},
},
question53{
para53{[]int{2, 7, 9, 3, 1}},
ans53{22},
},
question53{
para53{[]int{2}},
ans53{2},
},
question53{
para53{[]int{-1, -2}},
ans53{-1},
},
}
fmt.Printf("------------------------Leetcode Problem 53------------------------\n")
for _, q := range qs {
_, p := q.ans53, q.para53
fmt.Printf("【input】:%v 【output】:%v\n", p, maxSubArray(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,27 @@
# [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)
## 题目
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.
## 题目大意
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
## 解题思路
- 这一题可以用 DP 求解也可以不用 DP。
- 题目要求输出数组中某个区间内数字之和最大的那个值。`dp[i]` 表示 `[0,i]` 区间内各个子区间和的最大值,状态转移方程是 `dp[i] = nums[i] + dp[i-1] (dp[i-1] > 0)``dp[i] = nums[i] (dp[i-1] ≤ 0)`