最大サブセグメントと絶対値


#include <stdio.h>


typedef struct {
    size_t st;
    size_t end;
    int sum;
} ArraySection;


/*  , , ret */
void max_abs_section(int *arr, size_t len, ArraySection *ret_sec)
{
    size_t st_tmp = 0, end_tmp = 0;
    int sum_tmp = *arr;
    size_t i;
    ArraySection min_sec;
    ret_sec->st = ret_sec->end = 0;
    ret_sec->sum = sum_tmp;
    for (i = 1; i < len; ++i)
    {
        if (sum_tmp < 0)
        {
            end_tmp = st_tmp = i;
            sum_tmp = 0;
        }
        else
        {
            ++end_tmp;
        }
        sum_tmp += arr[i];
        if (sum_tmp > ret_sec->sum)
        {
            ret_sec->st = st_tmp;
            ret_sec->end = end_tmp;
            ret_sec->sum = sum_tmp;
        }
    }
    st_tmp = end_tmp = 0;
    min_sec.st = min_sec.end = 0;
    min_sec.sum = sum_tmp = *arr;
    for (i = 1; i < len; ++i)
    {
        if (sum_tmp > 0)
        {
            end_tmp = st_tmp = i;
            sum_tmp = 0;
        }
        else
        {
            ++end_tmp;
        }
        sum_tmp += arr[i];
        if (sum_tmp < min_sec.sum)
        {
            min_sec.st = st_tmp;
            min_sec.end = end_tmp;
            min_sec.sum = sum_tmp;
        }
    }
    if (min_sec.sum < 0 && (min_sec.sum + ret_sec->sum) < 0)
    {
        ret_sec->st = min_sec.st;
        ret_sec->end = min_sec.end;
        ret_sec->sum = -min_sec.sum;
    }
}


/*   */
int main()
{
    ArraySection as = { 0, 0, 0 };
    int arr[] = { -12, 23, 34, -4, -12523, 128 };
    max_abs_section(arr, sizeof(arr) / sizeof(*arr), &as);
    printf("st=%u
end=%u
sum=%i
", as.st, as.end, as.sum); }