zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    vxlan简介1
    什么underlay网络?
    CDN:内容分发网络
    zz博通发布用于数据中心交换机的开源软件开发套件SDKLT
    DPDK盒子使用手册——DPDK入门zz
    2018年最值得关注的15大技术趋势zz
    为什么要使用叶脊(leaf-spine)拓扑网络zz
    openvswitch
    Linux基础训练题型(下)
    Linux基础命令训练题型(上)
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3478543.html
Copyright © 2011-2022 走看看