zoukankan      html  css  js  c++  java
  • LeetCode Maximum Product Subarray(枚举)

                          LeetCode Maximum Product Subarray

    Description

    Given a sequence of integers S = {S1, S2, . . . , Sn}, you should determine what is the value of the maximum positive product involving consecutive terms of S. If you cannot find a positive sequence, you should consider 0 as the value of the maximum product.

    Input

    Each test case starts with 1 ≤ N ≤ 18, the number of elements in a sequence. Each element Si is an integer such that −10 ≤ Si ≤ 10. Next line will have N integers, representing the value of each element in the sequence. There is a blank line after each test case. The input is terminated by end of file (EOF).

    Output

    For each test case you must print the message: ‘Case #M: The maximum product is P.’, where M is the number of the test case, starting from 1, and P is the value of the maximum product. After each test case you must print a blank line.

    Sample Input

    3 2 4 -3 5 2 5 -1 2 -1

    Sample Output

    Case #1: The maximum product is 8.

    Case #2: The maximum product is 20.

    题意:

           输入n个元素组成的序列S,你需要找出一个乘积最大的连续子序列。如果这个最大的乘积不是正数,应输出0(表示无解)。每个案例要用空格隔开。

    题解:

           连续子序列有两个要素:起点和终点,因此只需枚举起点和终点即可。

           只要给最大值赋初值0,大于0才给最大值重新赋值,则任何负数最后输出都会为0,不需分开考虑。

           注意:最大值要用long long类。

    #include<iostream>
    #include<cstdio>
    using namespace std;
    int a[30];
    int main()
    {
        int k=0,t;
        while(scanf("%d",&t)==1)
        {
            long long maxn=0;
            for(int i=0; i<t; i++)
                cin>>a[i];
            for(int i=0; i<t; i++)
            {
                long long q=1;
                for(int j=i; j<t; j++)
                {
                    q=q*a[j];
                    if(q>maxn)
                        maxn=q;
                }
            }
            k++;
                printf("Case #%d: The maximum product is %lld.
    ",k,maxn);      
                printf("
    ");                // 注意格式啊
        }
        return 0;
    }
  • 相关阅读:
    Stanford NLP 第六课: Long Short Term Memory
    Stanford NLP 第五课: RNN Vanishing Gradient Problems Details
    Stanford NLP 第四课 神经网络复习
    Stanford cs224n 第三课: GloVe 代码解读
    Stanford CS224N 第二课: word2vec踩坑经验分享
    秒杀抢购系统优化思路详解
    微服务的事件驱动数据管理方案
    Netty与网络编程
    Netty 学习 一、初识Netty【原创】
    高性能Server---Reactor模型【转载】
  • 原文地址:https://www.cnblogs.com/hfc-xx/p/4684426.html
Copyright © 2011-2022 走看看