LeetCode刷题笔记(贪心):maximum-subarray

╰半橙微兮° 2022-06-01 11:19 195阅读 0赞

  • 转载请注明作者和出处:http://blog.csdn.net/u011475210
  • 代码地址:https://github.com/WordZzzz/Note/tree/master/LeetCode
  • 刷题平台:https://www.nowcoder.com/ta/leetcode
  • 题  库:Leetcode经典编程题
  • 编  者:WordZzzz

    • 题目描述
    • 解题思路
    • C版代码实现

题目描述

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array[−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray[4,−1,2,1]has the largest sum =6.

click to show more practice.

More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

在一个数组中找到连续的子数组(至少包含一个数字),这个数组的总和最大。 例如,给定数组[-2,1,-3,4,-1,2,1,-5,4],连续的子数组[4,-1,2,1]具有最大的和= 6。 更多的练习:如果你已经找到了O(n)的解决方案,尝试使用分而治之的方法编码另一个解决方案,这是更微妙的。

解题思路

从头开始累加,直到和为负。此时前面这段不能给后面的串带来正收益,应舍弃,sum清零,然后再开始统计最大的sum。算法时间复杂度O(n)。

题目中说可以尝试一下分治法,我是没想出来,后来看了leetcode上大神的代码才恍然大悟知道要怎么写。

For each subarray, calculate four attributes:

  1. mx (largest sum of this subarray),
  2. lmx(largest sum starting from the left most element),
  3. rmx(largest sum ending with the right most element),
  4. sum(the sum of the total subarray).

算法复杂度作者竟然说是O(n),但是我觉得是O(logn)?

  1. class Solution {
  2. public:
  3. void maxSubArray(vector<int>& nums, int l, int r, int& mx, int& lmx, int& rmx, int& sum) {
  4. if (l == r) {
  5. mx = lmx = rmx = sum = nums[l];
  6. }
  7. else {
  8. int m = (l + r) / 2;
  9. int mx1, lmx1, rmx1, sum1;
  10. int mx2, lmx2, rmx2, sum2;
  11. maxSubArray(nums, l, m, mx1, lmx1, rmx1, sum1);
  12. maxSubArray(nums, m + 1, r, mx2, lmx2, rmx2, sum2);
  13. mx = max(max(mx1, mx2), rmx1 + lmx2);
  14. lmx = max(lmx1, sum1 + lmx2);
  15. rmx = max(rmx2, sum2 + rmx1);
  16. sum = sum1 + sum2;
  17. }
  18. }
  19. int maxSubArray(vector<int>& nums) {
  20. if (nums.size() == 0) {
  21. return 0;
  22. }
  23. int mx, lmx, rmx, sum;
  24. maxSubArray(nums, 0, nums.size() - 1, mx, lmx, rmx, sum);
  25. return mx;
  26. }
  27. };

C++版代码实现

  1. class Solution {
  2. public:
  3. int maxSubArray(int A[], int n) {
  4. if(A == NULL || n == 0)
  5. return false;
  6. int sum = A[0];
  7. int maxSum = A[0];
  8. for(int i = 1; i < n; ++i){
  9. if(sum < 0)
  10. sum = 0;
  11. sum += A[i];
  12. maxSum = max(sum, maxSum);
  13. }
  14. return maxSum;
  15. }
  16. };

系列教程持续发布中,欢迎订阅、关注、收藏、评论、点赞哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

发表评论

表情:
评论列表 (有 0 条评论,195人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode笔记

    [23. Merge k Sorted Lists][] > 要点: > > 1. 学会数据结构PriorityQueue(优先队列)的用法, 通过给优先队列传入自定义