一些经典的编程题
连续最大子数组
#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;
}
有序数组中的重复子数组
#include <iostream>
using namespace std;
/**
* get the index range of repeat sub array
* @param arr the given array
* @param low the lowwer bound of the array
* @param high the upper bound of the array
*/
int get_repeat_arr(const int *arr, int low, int high, bool first_repeat) {
if (nullptr == arr || high <= low) {
return -1;
}
if (high - low == 1) {
if (arr[low] == arr[high]) {
if (first_repeat)
return low;
return high;
}
return -1;
}
int mid = (low + high) / 2;
if (first_repeat) {
int index_l = get_repeat_arr(arr, low, mid, first_repeat);
if (index_l >= 0)
return index_l;
else
return get_repeat_arr(arr, mid, high, first_repeat);
}
int index_r = get_repeat_arr(arr, mid, high, first_repeat);
if (index_r >= 0)
return index_r;
else
return get_repeat_arr(arr, low, mid, first_repeat);
}
int main() {
// int arr[] = {};
// int arr[] = {1};
// int arr[] = {-2,-2};
int arr[] = {-1, 0, 1, 2, 2, 2, 2, 2, 2, 15};
int size = sizeof(arr) / sizeof(int);
int index_1 = get_repeat_arr(arr, 0, size - 1, true);
int index_2 = get_repeat_arr(arr, 0, size - 1, false);
cout << index_1 << " " << index_2 << endl;
return 0;
}