连续最大字段和与最大字段积

求数组中满足给定和的数对

给定两个有序整型数组a和b,各有n个元素,求两个数组中满足给定和的数对,即对a中元素i和b中元素j,满足i + j = d(d已知)

分析

两个指针i和j分别指向数组的首尾,然后从两端同时向中间遍历,直到两个指针交叉。

代码

复制代码
// 找出满足给定和的数对
void FixedSum(int* a, int* b, int n, int d)
{
    for (int i = 0, j = n - 1; i < n && j >= 0)
    {
        if (a[i] + b[j] < d)
            ++i ;
        else if (a[i] + b[j] == d)
        {
            cout << a[i] << ", " << b[j] << endl ;
            ++i ;
            --j ;
        }
        else // a[i] + b[j] > d
            --j ;
    }
}
复制代码

最大子段和

给定一个整型数组a,求出最大连续子段之和,如果和为负数,则按0计算,比如1, 2, -5, 6, 8则输出6 + 8 = 14

分析

编程珠玑上的经典题目,不多说了。

代码

复制代码
// 子数组的最大和
int Sum(int* a, int n)
{
    int curSum = 0;
    int maxSum = 0;
    for (int i = 0; i < n; i++)
    {
        if (curSum + a[i] < 0)
            curSum = 0;
        else
        {
            curSum += a[i] ;
            maxSum = max(maxSum, curSum);
        }
    }
    return maxSum;
}
复制代码

最大子段积

给定一个整型数组a,求出最大连续子段的乘积,比如 1, 2, -8, 12, 7则输出12 * 7 = 84

分析

与最大子段和类似,注意处理负数的情况

代码

复制代码
// 子数组的最大乘积
int MaxProduct(int *a, int n)
{
    int maxProduct = 1; // max positive product at current position
    int minProduct = 1; // min negative product at current position
    int r = 1; // result, max multiplication totally

    for (int i = 0; i < n; i++)
    {
        if (a[i] > 0)
        {
            maxProduct *= a[i];
            minProduct = min(minProduct * a[i], 1);
        }
        else if (a[i] == 0)
        {
            maxProduct = 1;
            minProduct = 1;
        }
        else // a[i] < 0
        {
            int temp = maxProduct;
            maxProduct = max(minProduct * a[i], 1);
            minProduct = temp * a[i];
        }

        r = max(r, maxProduct);
    }

    return r;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值