Original title: https://oj.leetcode.com/problems/maximum-product-subarray/
For example, enter [2,3,-2,4]?
Qualifying sub-arrays should be [2,3], their product is 6
/** * @Author JIANGFQ * */package com.test;/** * @author JIANGFQ * */public class Solution {/** * @Author JIANGFQ * */pub Lic static void Main (string[] args) {int[] a = { -3,0,1,-2}; Solution s = new solution (); int b = S.maxproduct (a); System.out.println ("b=" + b);} public int maxproduct (int[] A) {if (a.length = = 0) {///if 0, return 0 return 0; } else if (a.length = = 1) {//If there is a return a[0]; } else if (a.length = = 2) {//If the array has two elements if (a[0] > A[0]*a[1]) {return a[0]; } else if (a[1] > A[0]*a[1]) {return a[1]; } return a[0]*a[1]; } else {int ood = 0;//record number of negative numbers int sum = 1; for (int i = 0; i < a.length; i++) {//Calculates negative numbers first and total product sum *= a[i]; if (A[i] < 0) {ood++; }} if (Ood!=0 && ood%2==0 && sum! = 0) {return sum; } else {int max = a[0]; Records the current maximum value int prev = max; Record the previous maximum value for easy comparison with current maximum for (int i = 0; i < a.length; i++) {max = a[i]; int s = max; if (s = = 0) {//If 0, skip continue; } for (int j = i+1; J < A.length; J + +) {s *= a[j]; if (Max < s) {max = s; }} if (prev < max) {prev = max; }} return prev; } } }}
Finds the maximum number of consecutive sub-arrays in an array