Code14 最大子序和

题目

leetcode53. 最大子序和
给定一个整数数组 nums,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

示例:
输入: [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

代码
  • 思路
    • 动态规划
      • 假设以下标 i 元素为结尾的最大子序和为 max_ending_here[i], 则有如下关系:
        max_ending_here[i] = max(max_ending_here[i-1] + nums[i], nums[i])   (i > 0)
        
  • 代码
// C
int maxSubArray(int* nums, int numsSize) {
  int max_ending_here = nums[0];
  int max_so_for = nums[0];
  for (int i = 1; i < numsSize; ++i) {
    max_ending_here = (max_ending_here + nums[i]) > nums[i]
                      ? (max_ending_here + nums[i]): nums[i];
    max_so_for = max_ending_here > max_so_for ? max_ending_here : max_so_for;
  }

  return max_so_for;
}

// C++
#include <algorithm>
#include <vector>
using namespace std;

class Solution {
 public:
  int maxSubArray(vector<int>& nums) {
    int max_ending_here = nums[0];
    int max_so_for = nums[0];
    for (int i = 1; i < nums.size(); ++i) {
      max_ending_here = std::max(max_ending_here + nums[i], nums[i]);
      max_so_for = std::max(max_ending_here, max_so_for);
    }

    return max_so_for;
  }
};
  • 注意
// 以下语句可换一种写法
max_ending_here = std::max(max_ending_here + nums[i], nums[i]);
// 如下:
if (max_ending_here > 0){  // max_ending_here + nums[i] > nums[i]
   max_ending_here = max_ending_here + nums[i];
}else{
   max_ending_here = nums[i];
}
测试
#include <iostream>

int main() {
  {
    // C
    int nums[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
    int n = sizeof(nums) / sizeof(nums[0]);
    cout << maxSubArray(nums, n) << endl;
  }
  {
    // C++
    vector<int> nums{-2, 1, -3, 4, -1, 2, 1, -5, 4};
    Solution s;
    cout << s.maxSubArray(nums) << endl;
  }

  cin.get();
  return 0;
}
  • 结果
6
6
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值