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;
    }
  • 相关阅读:
    Unity3D性能优化之美术资源制件规范
    Unity3D屏幕自适应
    Unity3D性能优化之内存科普篇
    面向对象设计和特性
    Uinty3D性能优化之贴图科普篇
    Learn OpenGL 概念(一)
    假如博客园也有年度总结报告……
    2019年修图汇总
    Python 小案例实战 —— 简易银行存取款查询系统
    Win10 + Anaconda + Tensorflow-cpu + Pycharm安装教程
  • 原文地址:https://www.cnblogs.com/hfc-xx/p/4684426.html
Copyright © 2011-2022 走看看