• LeetCode


    Maximum Subarray

    2013.12.17 14:21

    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.

    Solution:
      This is a typical problem on any Data Structure textbook. Need no further explanation.
      Time complexity is O(n), space complexity O(1).
    Accepted code:
     1 //#define __MAIN__
     2 #include <cstdio>
     3 #include <cstdlib>
     4 using namespace std;
     5 
     6 class Solution {
     7 public:
     8     int maxSubArray(int A[], int n) {
     9         // Note: The Solution object is instantiated only once and is reused by each test case.
    10         if(A == nullptr){
    11             return 0;
    12         }
    13 
    14         if(n <= 0){
    15             return 0;
    16         }
    17 
    18         int i;
    19         int max_value;
    20 
    21         max_value = A[0];
    22         for(i = 0; i < n; ++i){
    23             if(A[i] > max_value){
    24                 max_value = A[i];
    25             }
    26             if(A[i] >= 0){
    27                 break;
    28             }
    29         }
    30 
    31         if(i >= n && max_value <= 0){
    32             // All A[i]s are 0 or negative.
    33             return max_value;
    34         }
    35 
    36         int sum, max_sum;
    37 
    38         sum = max_sum = 0;
    39         for(i = 0; i < n; ++i){
    40             sum += A[i];
    41             if(sum < 0){
    42                 sum = 0;
    43             }
    44             if(sum > max_sum){
    45                 max_sum = sum;
    46             }
    47         }
    48 
    49         return max_sum;
    50     }
    51 };
    52 
    53 #ifdef __MAIN__
    54 int main()
    55 {
    56     Solution sol;
    57     int A[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
    58     const int n = sizeof(A) / sizeof(int);
    59 
    60     printf("%d
    ", sol.maxSubArray(A, n));
    61 
    62     return 0;
    63 }
    64 #endif
  • 相关阅读:
    「总结」容斥。二.反演原理 3.约数容斥
    「总结」容斥。二.反演原理 2.组合容斥
    「总结」容斥。二.反演原理 1.子集容斥
    「总结」容斥。一.容斥原理
    「考试」num (破800纪念)
    「刷题」 网络
    「考试」 Or
    「考试」weight
    「刷题」GERALD07加强版
    「刷题」Triple
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3478543.html
Copyright © 2020-2023  润新知