代码实现:
思路:最大子数组和
解法一:动态规划
#define max(a, b) ((a) > (b) ? (a) : (b))int maxSubArray(int* nums, int numsSize) {if (numsSize == 0) { // 特殊情况return 0;}int dp[numsSize];dp[0] = nums[0];int result = dp[0];for (int i = 1; i < numsSize; i++) {dp[i] = max(dp[i - 1] + nums[i], nums[i]); // 状态转移方程result = max(result, dp[i]); // result 保存dp[i]的最大值}return result; }
解法二:贪心
int maxSubArray(int *nums, int numsSize) {int result = INT32_MIN;int count = 0;for (int i = 0; i < numsSize; i++) {count += nums[i];if (count > result) { // 取区间累计的最大值(相当于不断确定最大子序终止位置)result = count;}if (count <= 0) {count = 0; // 相当于重置最大子序起始位置,因为遇到负数一定是拉低总和}}return result; }