编程之美-2.13 子数组最大乘积
来源:互联网 发布:360排名优化 编辑:程序博客网 时间:2024/06/08 01:16
问题描述:给定一个长度为N的数组,只允许用乘法,不允许用除法,计算任意N-1个数的组合乘积中的最大的一组,并写出算法时间复杂度。
按照编程之美一书中所描述的解法1,时间复杂度O(N)。
基本原理:第i个元素被排除在乘积之外,则其他N-1个元素之积 subProductI [ i ]=preI[i] *postI[i]; preI[i] 为第1-(i-1)个元素之积,postI[i]为第(i+1)-N个元素之积。
preI, postI都是通过从前向后以及从后向前依次扫描得到的数组。preI[i] = preI[i - 1] * v[i - 1]; postI[i] = postI[i + 1] * v[i+ 1]; v为原始输入数组。
代码如下:
#include <iostream>#include <vector>using namespace std;int findMaxProdSubArray(vector<int>v){int len = v.size();if (len<=1)return -1;vector<int>preI(len);vector<int>postI(len);vector<int>subProductI(len);preI[0] = 1;for (int i = 1; i < len; i++)preI[i] = preI[i - 1] * v[i - 1];postI[len-1] = 1;for (int i = len-2; i >=0; i--)postI[i] = postI[i + 1] * v[i+ 1];for (int i = 0; i <len; i++)subProductI[i] = preI[i] *postI[i];int max = subProductI[0];for (int i = 1; i <len; i++)if (max < subProductI[i])max = subProductI[i];return max;}
0 0
- 编程之美---子数组最大乘积
- 编程之美2.13 子数组的最大乘积
- 编程之美2.13 子数组的最大乘积
- 编程之美-2.13 子数组最大乘积
- 编程之美2.13 子数组的最大乘积
- 编程之美之"子数组的最大乘积"
- 编程之美--子数组中的最大乘积
- 子数组的最大乘积-编程之美
- 编程之美----子数组的最大乘积
- [编程之美]子数组的最大乘积
- 编程之美 子数组的最大乘积
- 编程之美:子数组的最大乘积
- 编程之美--子数组的最大乘积
- [编程之美] PSet2.13 子数组的最大乘积
- 编程之美 - 子数组的最大乘积
- 编程之美_子数组的最大乘积
- 读书笔记之编程之美 - 2.13 子数组的最大乘积
- 编程之美:第二章 数字之魅 2.13子数组的最大乘积
- Redis Jedis的使用(上)
- Kubernetes系列03:Guestbook示例:Hello World详解
- Roll模型—高频交易择时策略的有效解决方法
- hibernate学习笔记5 ------ 缓存,注解
- 转导推理——Transductive Learning
- 编程之美-2.13 子数组最大乘积
- Linux学习篇第二章~unit3
- Ubuntu下安装Chrome浏览器的两个方法
- cisco 的网络地址转换技术(NAT)
- MySQL数据类型
- Til the Cows Come Home 【SPFA】 【djk】
- 集合框架
- Codeforces Round #409 (rated, Div. 2, based on VK Cup 2017 Round 2)
- 简单的输入