一些经典的编程题
连续最大子数组
#include <iostream>
using namespace std;
/**
* get the index of max sum sub array and the sum
* @param arr the given array
* @param low the lowwer bound of the array
* @param high the upper bound of the array
*/
void get_max_arr(const int *arr, int low, int high) {
if(nullptr == arr || high < 0){
return;
}
int sum = -9999,temp_sum = 0;
int begin = 0, index_1 = 0, index_2 = 0;
for (int i = low; i <= high; ++i) {
temp_sum += arr[i];
if (temp_sum > sum) {
sum = temp_sum;
index_2 = i;
index_1 = begin;
}
if (temp_sum < 0) {
temp_sum = 0;
begin = i + 1;
}
}
cout << index_1 << " " << index_2 << endl;
cout << sum << endl;
}
int main() {
// int arr[] = {};
int arr[] = {-2,-2,-3};
// int arr[] = {-1, 0, 2, -2, -3, 4, 5, -9, 3, -5};
// int arr[] = {-9, -2, -3, -4, -5, -9, -3, -5};
int size = sizeof(arr) / sizeof(int);
get_max_arr(arr, 0, size - 1);
return 0;
}