题意:

image.png

解题思路:

  1. 思路:
  2. DP两部曲
  3. 1.状态定义:dp[i]: i下标的时候连续的最大和
  4. 2.状态转移方程:如果dp[i] = if 如果dp[i - 1]是负数,那么dp[i] = nums[$i]
  5. else dp[i] = dp[i - 1] + nums[i]

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer[] $nums
  4. * @return Integer
  5. */
  6. function maxSubArray($nums) {
  7. return $this->maxSubArrayDP($nums);
  8. $sum = 0;
  9. $ans = $nums[0];
  10. foreach ($nums as $num) {
  11. $sum = $sum > 0 ? ($sum += $num) : $num;
  12. $ans = max($ans, $sum);
  13. }
  14. return $ans;
  15. }
  16. function maxSubArrayDP($nums) {
  17. if (!$nums) return 0;
  18. $dp = [];
  19. $dp[0] = $nums[0];
  20. $max = $nums[0];
  21. for ($i = 1; $i < count($nums); $i++) {
  22. $dp[$i] = $dp[$i - 1] < 0 ? $nums[$i] : $dp[$i - 1] + $nums[$i];
  23. $max = max($max, $dp[$i]);
  24. }
  25. return $max;
  26. }
  27. function maxSubArrayForce($nums) {
  28. $max = PHP_INT_MIN;
  29. for ($i = 0; $i < count($nums); $i++) {
  30. $sum = 0;
  31. for ($j = $i; $j < count($nums); $j++) {
  32. $sum += $nums[$j];
  33. if ($sum > $max) $max = $sum;
  34. }
  35. }
  36. return $max;
  37. }
  38. }

GO代码实现:

  1. func maxSubArray(nums []int) int {
  2. maxNum := nums[0]
  3. dp := make([]int, len(nums))
  4. dp[0] = nums[0]
  5. for i := 1; i < len(nums); i++ {
  6. dp[i] = max(dp[i-1] + nums[i], nums[i])
  7. maxNum = max(maxNum, dp[i])
  8. }
  9. return maxNum
  10. }
  11. func max(i, j int) int {
  12. if i > j {
  13. return i
  14. }
  15. return j
  16. }
  1. func maxSubArray(nums []int) int {
  2. l := len(nums)
  3. max := nums[0]
  4. for i:=1; i<l; i++ {
  5. if nums[i-1] > 0 {
  6. nums[i] += nums[i-1]
  7. }
  8. if nums[i] > max {
  9. max = nums[i]
  10. }
  11. }
  12. return max
  13. }