UVA 11059 - Maximum Product( 暴力 & dp之LIS )

本文探讨如何在一组数据中找到乘积最大的连续子序列,通过暴力与动态规划两种方法进行解决。介绍了两种实现思路,并提供了相应的代码实现。

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2000

题       意:在一组数据中找出乘积最大的连续子序列。

思      路:暴力与动态规划都可以。

               1.暴力枚举开始于结束位置。

代码如下:

#include <iostream>
using namespace std;
#include <string.h>
#include <stdio.h>
#include <queue>
#include <algorithm>
typedef long long LL;
int vis[30];
int main()
{
    int n, cas = 1;
    while( scanf ( "%d", &n ) != EOF )
    {
        LL ans = 0;
        for( int i = 1; i <= n; i ++ )
        {
            scanf ( "%d", &vis[i] );
        }
        for( int i = 1; i <= n; i ++ )
        {
            LL sum = 1;
            for( int j = i; j <= n; j ++ )
            {
                sum*=vis[j];
                if( ans < sum ) ans = sum;
            }
        }
        if(ans<0) ans = 0;
        printf("Case #%d: The maximum product is %lld.\n\n",cas++,ans);
    }
    return 0;
}

               2.设置最大的正数与最小的负数两个变量,对于数组vis[n]中的数,若大于等于0则对应更新,若小于0则更新后,交换两个变量的值。

代码如下:

#include <iostream>
using namespace std;
#include <string.h>
#include <stdio.h>
#include <queue>
#include <algorithm>
typedef long long LL;
int vis[30];
int main()
{
    int n, cas = 1;
    while( scanf ( "%d", &n ) != EOF )
    {
        LL ans = -1, z = 0, f = 0;
        for( int i = 1; i <= n; i ++ )
        {
            scanf ( "%d", &vis[i] );
            if( vis[i] >= 0 )
            {
                z*=vis[i];
                f*=vis[i];
                if(!z) z=vis[i];
            }
            else
            {
                LL t = z*vis[i];
                z = f*vis[i];
                f = t;
                if( !f ) f = vis[i];
            }
            if( ans < z )
                ans = z;
        }
        if(ans<0) ans = 0;
        printf("Case #%d: The maximum product is %lld.\n\n",cas++,ans);
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值