1. 程式人生 > >最近遇到的一些編程題

最近遇到的一些編程題

down dex 經典 pos mes 編程 {} index logs

一些經典的編程題

連續最大子數組

#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; }

最近遇到的一些編程題