我的相关文章:
【1】牛客网在线编程专题《剑指offer-面试题31》连续子数组的最大和
53. Maximum Subarray
Description:
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.
解题思路:
(1)举例分析数组的规律
已经AC的代码:
public class solutionMaxSubArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(maxSubArray(arr));
}
public static int maxSubArray(int[] nums) {
int sum = Integer.MIN_VALUE;
int currentSum = 0;
for(int i=0; i<nums.length; i++) {
currentSum += nums[i];
if(currentSum < nums[i]) {
currentSum = nums[i];
}
if(currentSum > sum) {
sum = currentSum;
}
}
return sum;
}
}
(2)动态规划的解法
public class solutionMaxSubArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(maxSubArray(arr));
}
public static int maxSubArray(int[] nums) {
int sum = Integer.MIN_VALUE;
int currentSum = 0;
for(int i=0; i<nums.length; i++) {
if(currentSum <= 0)
currentSum = nums[i];
else
currentSum += nums[i];
if(currentSum > sum)
sum = currentSum;
}
return sum;
}
}
Python已经AC的代码:
class Solution:
def maxSubArray(self, nums):
nums_len = len(nums)
result = [0 for i in range(nums_len)]
maxSum = result[0] = nums[0]
for i in range(1, nums_len):
if nums[i] >= result[i-1] + nums[i]:
result[i] = nums[i]
else:
result[i] = result[i-1] + nums[i]
if maxSum <= result[i]:
maxSum = result[i]
return maxSum
if __name__ == '__main__':
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
sol = Solution()
print(sol.maxSubArray(nums))
最大子数组和算法解析

345

被折叠的 条评论
为什么被折叠?



