当前位置:   article > 正文

C++ | Leetcode C++题解之第53题最大子数组和

C++ | Leetcode C++题解之第53题最大子数组和

题目:

题解:

  1. class Solution {
  2. public:
  3. struct Status {
  4. int lSum, rSum, mSum, iSum;
  5. };
  6. Status pushUp(Status l, Status r) {
  7. int iSum = l.iSum + r.iSum;
  8. int lSum = max(l.lSum, l.iSum + r.lSum);
  9. int rSum = max(r.rSum, r.iSum + l.rSum);
  10. int mSum = max(max(l.mSum, r.mSum), l.rSum + r.lSum);
  11. return (Status) {lSum, rSum, mSum, iSum};
  12. };
  13. Status get(vector<int> &a, int l, int r) {
  14. if (l == r) {
  15. return (Status) {a[l], a[l], a[l], a[l]};
  16. }
  17. int m = (l + r) >> 1;
  18. Status lSub = get(a, l, m);
  19. Status rSub = get(a, m + 1, r);
  20. return pushUp(lSub, rSub);
  21. }
  22. int maxSubArray(vector<int>& nums) {
  23. return get(nums, 0, nums.size() - 1).mSum;
  24. }
  25. };
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/687069
推荐阅读
相关标签
  

闽ICP备14008679号