当前位置:网站首页>力扣152题乘数最大子数组
力扣152题乘数最大子数组
2022-07-06 09:22:00 【ai其实很简单】
152.乘数最大子数组
问题描述: 给你一个整数数组 nums ,请你找出数组中乘积最大的非空连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
测试用例的答案是一个 32-位 整数。
子数组 是数组的连续子序列。
策略: 本题为动态规划的题,可以自底向上的求解答案,遍历整个数组计算当前的最大值用imax进行记录,不断更新最终求解出答案。由于数组中有负数,会将最大值变为最小值,最小值变成最大值,所以需要imin进行记录最小值。当求第i个数时:若该点的值为正数,则该点的最大值可能为前一个数的最大值乘该点的值,或者是该点的值(imax=fmax(imaxnums[i],nums[i]))最小值为(imin=fmin(iminnums[i],nums[i]););若该点的值为负数,将最大值与最小值进行交换,再进行求解。
代码:
int maxProduct(int* nums, int numsSize){
int imax=1,imin=1,max=INT_MIN;
for(int i=0;i<numsSize;i++){
if(nums[i]<0){
//当遇见负数的时候最大值会变成最小值,最小值变成最大值 此时交换位置
int temp=imin;
imin=imax;
imax=temp;
}
imax=fmax(imax*nums[i],nums[i]);
imin=fmin(imin*nums[i],nums[i]);
max=fmax(max,imax); //过去的最大值与该点的最大值进行比较
}
return max;
}
边栏推荐
- 5月27日杂谈
- Write a program to simulate the traffic lights in real life.
- 强化学习系列(一):基本原理和概念
- [modern Chinese history] Chapter V test
- 7-7 7003 组合锁(PTA程序设计)
- Using spacedesk to realize any device in the LAN as a computer expansion screen
- Wei Pai: the product is applauded, but why is the sales volume still frustrated
- vector
- SRC挖掘思路及方法
- 8.C语言——位操作符与位移操作符
猜你喜欢

记一次猫舍由外到内的渗透撞库操作提取-flag

2022 Teddy cup data mining challenge question C idea and post game summary

Write a program to simulate the traffic lights in real life.

Caching mechanism of leveldb

Leetcode. 3. Longest substring without repeated characters - more than 100% solution

.Xmind文件如何上传金山文档共享在线编辑?

Mode 1 two-way serial communication is adopted between machine a and machine B, and the specific requirements are as follows: (1) the K1 key of machine a can control the ledi of machine B to turn on a

3. Input and output functions (printf, scanf, getchar and putchar)
![[面試時]——我如何講清楚TCP實現可靠傳輸的機制](/img/d6/109042b77de2f3cfbf866b24e89a45.png)
[面試時]——我如何講清楚TCP實現可靠傳輸的機制

【手撕代码】单例模式及生产者/消费者模式
随机推荐
MySQL lock summary (comprehensive and concise + graphic explanation)
string
vector
Caching mechanism of leveldb
受检异常和非受检异常的区别和理解
C语言入门指南
[the Nine Yang Manual] 2020 Fudan University Applied Statistics real problem + analysis
渗透测试学习与实战阶段分析
Beautified table style
7-15 h0161. 求最大公约数和最小公倍数(PTA程序设计)
C language Getting Started Guide
[the Nine Yang Manual] 2016 Fudan University Applied Statistics real problem + analysis
Mortal immortal cultivation pointer-2
FAQs and answers to the imitation Niuke technology blog project (II)
Reinforcement learning series (I): basic principles and concepts
8.C语言——位操作符与位移操作符
2022 Teddy cup data mining challenge question C idea and post game summary
3. Number guessing game
TypeScript快速入门
编写程序,模拟现实生活中的交通信号灯。