算法导论-第四章-分治策略:最大子数组C++实现

#include <iostream>
#include <limits>
#include <vector>
#include <array>
#include <algorithm>
using namespace std;

array<int, 3> find_max_cross_subarray(int A[], int low, int mid, int high) {
    int left_sum = numeric_limits<int>::min();
    int max_left {};
    int sum {};
    for(int i = mid; i >= low; --i) {
        sum += A[i];
        if(sum > left_sum) {
            left_sum = sum;
            max_left = i;
        }
    }
    
    int right_sum = numeric_limits<int>::min();
    int max_right {};
    sum = 0;
    for(int i = mid + 1; i <= high; ++i) {
        sum += A[i];
        if(sum > right_sum) {
            right_sum = sum;
            max_right = i;
        }
    }
    return array<int, 3>{ max_left, max_right, left_sum + right_sum };
}

array<int, 3> find_maximum_subarray(int A[], int low, int high) {
    
    int mid {};
    if(high == low)
        return array<int, 3> { low, high, A[low] };
    else {
        mid = (low + high) / 2;
        array<int, 3> left_maximum = find_maximum_subarray(A, low, mid);
        array<int, 3> right_maximum = find_maximum_subarray(A, mid + 1, high);
        array<int, 3> cross_mid_maximum = find_max_cross_subarray(A, low, mid, high);
        
        if(left_maximum[2] >= right_maximum[2] && left_maximum[2] >= cross_mid_maximum[2])
            return array<int, 3> { left_maximum[0], left_maximum[1], left_maximum[2] };
        else if(right_maximum[2] >= left_maximum[2] && right_maximum[2] >= cross_mid_maximum[2])
            return array<int, 3> { right_maximum[0], right_maximum[1], right_maximum[2] };
        else
            return array<int, 3> { cross_mid_maximum[0], cross_mid_maximum[1], cross_mid_maximum[2] };
    }
}

int main(int argc, const char * argv[]) {
    
    vector<int> input {};
    cout << "please input the array :(you can input noninterger to finish your input)" << endl;
    int element;
    while(cin >> element) {
        input.push_back(element);
    }
    int* A = new int[input.size()];
    int index {};
    for_each(input.begin(), input.end(), [=](int x)mutable{ A[index++] = x; });
    array<int, 3> result = find_maximum_subarray(A, 0, static_cast<int>(input.size() - 1));
    cout << "the max subarray from :" << result[0] + 1 << "th to "<< result[1] + 1 << "th, and the sum is : " << result[2] << endl;
    delete []A;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值