[nowCoder] 子数组最大乘积】的更多相关文章

给定一个double类型的数组arr,其中的元素可正可负可0,返回子数组累乘的最大乘积.例如arr=[-2.5,4,0,3,0.5,8,-1],子数组[3,0.5,8]累乘可以获得最大的乘积12,所以返回12. 分析,是一个dp的题目, 设f[i]表示以i为结尾的最大值,g[i]表示以i结尾的最小值,那么 f[i+1] = max{f[i]*arr[i+1], g[i]*arr[i+1],arr[i+1]} ,只有这三种情况. 考虑到f[i],g[i]只和i-1有关,那么可以用局部变量即可搞定,…
Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4],the contiguous subarray [2,3] has the largest product = 6. 很显然是一个动态规划的问题,找到递归表达式就可以了,考虑到会有负负相乘的问题,所以应…
题目链接:https://leetcode.com/problems/maximum-product-subarray/description/ 题目大意:给出一串数组,找出连续子数组中乘积最大的子数组的乘积. 法一:暴力.竟然能过,数据也太水了.两个for循环,遍历每一个可能的连续子数组,找出最大值.代码如下(耗时161ms): public int maxProduct(int[] nums) { int res = Integer.MIN_VALUE, len = nums.length;…
1. 子数组的最大和 输入一个整形数组,数组里有正数也有负数.数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和.求所有子数组的和的最大值.例如数组:arr[]={1, 2, 3, -2, 4, -3 } 最大子数组为 {1, 2, 3, -2, 4} 和为8. 解法1(时间复杂度O(N * N)空间复杂度O(1)) 求出所有的子数组的和,比较选择出最大值.利用双重循环就可以遍历到所有的子数组. public static void maxSum1(int arr[]) { int…
分析,是一个dp的题目, 设f[i]表示以i为结尾的最大值,g[i]表示以i结尾的最小值,那么 f[i+1] = max{f[i]*arr[i+1], g[i]*arr[i+1],arr[i+1]} ,只有这三种情况. 考虑到f[i],g[i]只和i-1有关,那么可以用局部变量即可搞定,而不用使用数组. 1 import java.lang.Math; public class Solution { public double maxProduct(double[] arr) { double…
Your are given an array of positive integers nums. Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k. Example 1: Input: nums = [10, 5, 2, 6], k = 100 Output: 8 Explanation: The 8…
Your are given an array of positive integers nums. Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k. Example 1: Input: nums = [10, 5, 2, 6], k = 100 Output: 8 Explanation: The 8…
Add Date 2014-09-23 Maximum Product Subarray Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4],the contiguous subarray [2,3] has the largest product = …
713. 乘积小于K的子数组 给定一个正整数数组 nums. 找出该数组内乘积小于 k 的连续的子数组的个数. 示例 1: 输入: nums = [10,5,2,6], k = 100 输出: 8 解释: 8个乘积小于100的子数组分别为: [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6]. 需要注意的是 [10,5,2] 并不是乘积小于100的子数组. 说明: 0 < nums.length <= 50000 0 < nums[i]…
题目: 输入一个整型数组,数组里有正数也有负数,数组中一个或连续多个整数组成一个子数组,求所有子数组的和的最大值.要求时间复杂度为O(n) 思路: 1.数组累加 从头到尾逐个累加数组中的每个数字,当累加之和小于0时,从下一个元素开始累加,并通过一个变量保存最大和. 2.动态规划 思路与1一样,假设f(i)为以第i个数字结尾的子数组的最大和,那么 f(i)=A[i], f(i-1)<=0 f(i)=f(i-1)+A[i],f(i-1)>0 初始状态:f(0)=A[0] 最后求max(f(i)).…