53. Maximum Subarray (Kadane算法 / 动态规划 / 分治法)

本文介绍了LeetCode上的最大子数组问题,通过Kadane算法、动态规划和分治法三种方法进行求解。Kadane算法通过遍历数组,当累加结果小于或等于0时,从下一个元素开始重新累加。动态规划则维护全局最优和局部最优两个变量,通过递推式找到最大子数组。分治法将数组分为两部分,分别求解最大子数组,并结合中间元素求解。
摘要由CSDN通过智能技术生成

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.

【分析】

这是一道非常简单的算法题,但是实现的方法却有很多种。在本篇文章中,博主想介绍三种巧妙的方法,这三种方法在面试和刷题过程中有非常广泛的应用。

方法一:Kadane算法

算法描述:

  1. 遍历该数组, 在遍历过程中, 将遍历到的元素依次累
分治法求解最大子段和(Maximum Subarray Problem)通常使用的是Kadane's Algorithm,这是一个经典的动态规划问题。下面是它的基本伪代码: ```plaintext function maxSubArraySum(arr, low, high): // Base case: If array has only one element if low == high: return arr[low] // Middle index mid = (low + high) // 2 // Recursively find the maximum subarray sum in left and right halves max_left_sum = maxSubArraySum(arr, low, mid) max_right_sum = maxSubArraySum(arr, mid+1, high) // Find the maximum of following three cases # a) Maximum subarray with elements till mid # b) Maximum subarray with elements after mid # c) Maximum subarray with both first and last elements of the current subarray max_cross_sum = arr[mid] for i from low to mid - 1: max_cross_sum = max(max_cross_sum, arr[i] + arr[mid]) // Return the maximum of these three sums return max(max_left_sum, max_right_sum, max_cross_sum) // Call the function on the given array arr = [your_array_elements] // Replace this with your array n = length of arr return maxSubArraySum(arr, 0, n-1) ``` 在这个算法中,我们首先检查数组是否只有一个元素,如果是,则直接返回这个元素。然后我们将数组分为两半,分别递归地计算左半部分和右半部分的最大子段和。接着,我们在跨越中间点的情况下寻找最大和,这可以通过遍历左半部分的每个元素并加上中间点的值来完成。最后,我们比较这三个可能的最大和并返回结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值