分而治之策略-最大子数组(java、c++、python)

这篇博客介绍了求解无序数组最大子数组和的三种算法:简单枚举法、进阶枚举法和归并法。简单枚举法时间复杂度为O(n^3),进阶枚举法通过优化降低到O(n^2)。归并法利用分治思想,结合线性扫描,达到O(nlogn)的时间复杂度。每种方法都提供了C++、Java和Python的代码实现。

最大子数组和


问题

给定一个无序数组,求其最大子数组和。 s u b A r r subArr subArr a r r arr arr的子数组即是说 a u b A r r aubArr aubArr a r r arr arr中的某一段分片, s u b A r r subArr subArr的子数组和即为该段分片中所有元素之和。具有最大子数组和的子数组记为最大子数组。


简单枚举法
  1. 列举所有可能的子数组,记录最大子数组和。
  2. 一个长度为 n n n的数组存在 n ( n + 1 ) / 2 n(n+1)/2 n(n+1)/2个非空子数组,故遍历子数组时间复杂度为 O ( n 2 ) O(n^2) O(n2)
  3. 每次遍历需要对当前子数组进行求和,可得求和为线性时间复杂度 O ( n ) O(n) O(n)
  4. 故简单枚举法的时间复杂度为 O ( n 3 ) O(n^3) O(n3)

代码

  1. c++

    #include <vector>
    #include <climits>
    #include <exception>
    using std::vector;
    using std::exception;
    
    class MaxSub {
    public :
        int max_sub(vector<int>& arr) {
            if (arr.size() == 0) // 数组判空
                throw exception("arr cannot be empty!");
            int size = arr.size();
            int sum = INT_MIN, temp = 0; // sum初始化为int最小值
            for (int i = 0; i < size; i++) {
                for (int j = i; j < size; j++) {
                    temp = 0;
                    for (int k = i; k <= j; k++)
                        temp += arr[k];
                    if (temp > sum)
                        sum = temp;
                }
            }
            return sum;
        }
    };
    
  2. java

    import java.lang.RuntimeException;
    
    public class MaxSub{
        public int max_sub(int[] arr) {
            if (arr.length == 0)  // 数组判空
            	throw new RuntimeException("arr cannot be empty!");
            int sum = Integer.MIN_VALUE; // sum初始化为int最小值
            int temp = 0;
            for (int i = 0; i < arr.length; i++) {
                for (int j = i; j < arr.length; j++) {
                    temp = 0;
                    for (int k = i; k <= j; k++)
                        temp += arr[k];
                    if (temp > sum)
                        sum = temp;
                }
            }
            return sum;
        }
    }
    
  3. python

    class MaxSub:
        def max_sub(self, arr: list) -> int:
            if len(arr) == 0: # 数组判空
                raise Exception("arr cannot be empty!")
            sum = float("-inf") # sum初始化为负无穷
            for i in range(len(arr)):
                for j in range(i,len(arr)):
                    temp = 0
                    for k in range(i,j+1):
                        temp += arr[k]
                    if sum < temp:
                        sum = temp
            return sum
    

进阶枚举法
  1. 对于简单枚举法,考虑到每次遍历的求和,可以基于前一次的结果,即当次子数组的和为上一个不包含当前元素的子数组和加上当前元素的值,故此每次遍历求数组和的时间复杂度变为 O ( 1 ) O(1) O(1)
  2. 进阶枚举法的时间复杂度为 O ( n 2 ) O(n^2) O(n2)

代码

  1. c++

    #include <vector>
    #include <climits>
    #include <exception>
    using std::vector;
    using std::exception;
    
    class MaxSub {
    public :
        int max_sub(vector<int>& arr) {
            if (arr.size() == 0) // 数组判空
            	throw exception("arr cannot be empty!");
            int size = arr.size();
            int sum = INT_MIN, temp = 0;
            for (int i = 0; i < size; i++) {
                temp = 0;
                for (int j = i; j < size; j++) {
                    temp += arr[j];
                    if (temp > sum)
                        sum = temp;
                }
            }
            return sum;
        }
    };
    
  2. java

    import java.lang.RuntimeException;
    
    public class Linshi{
        public int max_sub(int[] arr) {
            if (arr.length == 0) // 数组判空
            	throw new RuntimeException("arr cannot be empty!");
            int sum = Integer.MIN_VALUE;
            int temp = 0;
            for (int i = 0; i < arr.length; i++) {
                temp = 0;
                for (int j = i; j < arr.length; j++) {
                    temp += arr[j];
                    if (temp > sum)
                        sum = temp;
                }
            }
            return sum;
        }
    }
    
  3. python

    class MaxSub:
        def max_sub(self, arr: list) -> int:
            if len(arr) == 0:
                raise Exception("arr cannot be empty!")
            sum = float("-inf")
            for i in range(len(arr)):
                temp = 0
                for j in range(i,len(arr)):
                    temp += arr[j]
                    if sum < temp:
                        sum = temp
            return sum
    

归并法
  1. 借鉴归并排序思想,求解一个数组的最大子数组,可以将原数组一分为二,分别考虑去求解每个数组的最大子数组,显然可以借助递归实现。
  2. 不同于归并排序,这里还需要考虑另一种情况,即划分为左右长度n/2的数组,其最大子数组既不存在于左侧数组,也不存在于右侧数组,而是跨越一段从左侧跨越到右侧数组的子数组。
  3. 将左侧数组的最大子数组和记为sum_left,右侧数组的最大子数组和记为sum_right,跨越左右两侧的最大子数组和记为sum_cross,则递归中每次回溯只需比较上面三者的最大值返回,即 m a x { s u m _ l e f t , s u m _ r i g h t , s u m _ c r o s s } max\{sum\_left, sum\_right, sum\_cross\} max{sum_left,sum_right,sum_cross}
  4. 对于sum_left和sum_right,一个长度为n的数组,一分为二后即分别求解左右两侧长度为n/2的数组的最大子数组,当递归深度足够大,左右两侧只有一个元素时,各自的最大子数组即为其元素本身,易得sum_left和sum_right.
  5. 对于sum_cross,不难发现,其由于既不属于左侧数组,也不数组右侧数组,故必定包含左侧数组最后一个元素和右侧数组第一个元素,借助上面枚举的思想,可以以这两个中间元素为基础,分别向左和向右累加元素,得到分别包含这两个中间元素的左右侧最大子数组,相加即为sum_cross.
  6. 综上,每次回溯获取sum_left与sum_right的时间复杂度为 O ( 1 ) O(1) O(1),获取sum_cross的时间复杂度为 O ( n ) O(n) O(n)(从中间向左右两侧线性遍历),递归分割的时间复杂度为 O ( l o g n ) O(logn) O(logn),故归并法的时间复杂度为 O ( n l o g n ) O(nlogn) O(nlogn)

代码

  1. c++

    #include <vector>
    #include <exception>
    using std::vector;
    using std::exception;
    
    class MaxSub {
    public :
        int max_sub(vector<int>& arr) { // 对外调用接口
            if (arr.size() == 0) // 数组判空
                throw exception("arr cannot be empty!");
            else 
    	        return this->_max_sub(arr, 0, arr.size());
        }
    private :
        int _max_sub(vector<int>& arr, int left, int right) { // 内部递归实现
            if (left + 1 == right) // 只有一个元素时递归终止
                return arr[left];
            int mid = (left + right) / 2;
            int sum_left = this->_max_sub(arr, left, mid); // 左侧数组最大子数组和
            int sum_right = this->_max_sub(arr, mid, right); // 右侧数组最大子数组和
            // 跨越中间数组最大子数组和
            int left_cross = arr[mid - 1], temp = 0;
            for (int i = mid - 1; i >= left; i--) {
                temp += arr[i];
                if (temp > left_cross)
                    left_cross = temp;
            }
            int right_cross = arr[mid];
            temp = 0;
            for (int i = mid; i < right; i++) {
                temp += arr[i];
                if (temp > right_cross)
                    right_cross = temp;
            }
            int sum_cross = left_cross + right_cross;
            // 判断返回三者最大值
            if (sum_left >= sum_right && sum_left >= sum_cross)
                return sum_left;
            if (sum_right >= sum_left && sum_right >= sum_cross)
                return sum_right;
            if (sum_cross >= sum_left && sum_cross >= sum_right)
                return sum_cross;
        }
    };
    
  2. java

    import java.lang.RuntimeException;
    
    public class Linshi{   
        public int max_sub(int[] arr) { // 对外调用接口
            if (arr.length == 0) // 数组判空
                throw new RuntimeException("arr cannot be empty!");
            else 
                return this._max_sub(arr, 0, arr.length);
        }
        
        private int _max_sub(int[] arr, int left, int right) { // 内部递归实现
            if (left + 1 == right) // 只有一个元素时递归终止
                return arr[left];
            int mid = (left + right) / 2;
            int sum_left = this._max_sub(arr, left, mid); // 左侧数组最大子数组和
            int sum_right = this._max_sub(arr, mid, right); // 右侧数组最大子数组和
            // 跨越中间数组最大子数组和
            int left_cross = arr[mid - 1], temp = 0;
            for (int i = mid - 1; i >= left; i--) {
                temp += arr[i];
                if (temp > left_cross)
                    left_cross = temp;
            }
            int right_cross = arr[mid];
            temp = 0;
            for (int i = mid; i < right; i++) {
                temp += arr[i];
                if (temp > right_cross)
                    right_cross = temp;
            }
            int sum_cross = left_cross + right_cross;
            // 判断返回三者最大值
            if (sum_left >= sum_right && sum_left >= sum_cross)
                return sum_left;
            else if (sum_right >= sum_left && sum_right >= sum_cross)
                return sum_right;
            else 
                return sum_cross;
        }
    }
    
  3. python

    class MaxSub:
        def max_sub(self, arr: list) -> int: # 对外调用接口
            if len(arr) == 0: # 数组判空
                raise Exception("arr cannot be empty!")
            else :
    	        return self.__max_sub(arr, 0, len(arr))
        def __max_sub(self, arr: list, left: int, right: int) -> int: # 内部递归实现
            if left + 1 == right: # 只有一个元素时终止递归
                return arr[left]
            mid = (left + right) // 2 # 索引折半
            sum_left = self.__max_sub(arr, left, mid) # 左侧最大子数组和
            sum_right = self.__max_sub(arr, mid, right) # 右侧最大子数组和
            # 跨越中间最大子数组和
            left_cross = arr[mid - 1]
            temp = 0
            i = mid - 1
            while i >= left:
                temp += arr[i]
                if temp > left_cross:
                    left_cross = temp
                i -= 1
            right_cross = arr[mid]
            temp = 0
            i = mid
            while i < right:
                temp += arr[i]
                if right_cross < temp:
                    right_cross = temp
                i += 1
            cross_max = left_cross + right_cross
            # 判断返回三者最大值
            return max(sum_left, sum_right, cross_max)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值