LeetCode 题解(57): 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 = 6.

题解:

如果为零,重新计算local_max,否则,保持一个正值和一个负值。

C++版:

class Solution {
public:
    int maxProduct(int A[], int n) {
        if(n == 1)
            return A[0];
            
        vector<int> local;
        local.push_back(A[0]);
        int global = A[0];
        
        for(int i = 1; i < n; i++) {
            if(!local[0]) {
                local.clear();
                local.push_back(A[i]);
            }
            else {
                for(int k = 0; k < local.size(); k++)
                    local[k] *= A[i];
                if(local.size() == 1 && local[0] * A[i] < 0)
                    local.push_back(A[i]);
            }
            for(int j = 0; j < local.size(); j++)
                if(local[j] > global)
                    global = local[j];
        }
        return global;
    }
};

Java版:

import java.util.*;

public class Solution {
    public int maxProduct(int[] A) {
        if(A.length == 1)
            return A[0];
            
        Vector<Integer> local = new Vector<Integer>();
        local.add(A[0]);
        int global = A[0];
        
        for(int i = 1; i < A.length; i++) {
            if(local.elementAt(0) == 0) {
                local.clear();
                local.add(A[i]);
            }
            else {
                for(int j = 0; j < local.size(); j++) {
                    local.set(j, A[i] * local.elementAt(j));
                }
                if(local.size() == 1 && local.elementAt(0) * A[i] < 0)
                    local.add(A[i]);
            }
            for(int k = 0; k < local.size(); k++)
                if(local.elementAt(k) > global)
                    global = local.elementAt(k);
        }
        return global;
    }
}

Python版:

class Solution:
    # @param A, a list of integers
    # @return an integer
    def maxProduct(self, A):
        if len(A) == 1:
            return A[0]
        local_max = [A[0]]
        global_max = A[0]
        for i in range(1, len(A)):
            if local_max[0] == 0:
                local_max = [A[i]]
            else:
                for j in range(len(local_max)):
                    local_max[j] = local_max[j] * A[i]
                if len(local_max) == 1 and local_max[0] * A[i] < 0:
                    local_max.append(A[i])
                
            for k in range(len(local_max)):
                if local_max[k] > global_max:
                    global_max = local_max[k]
                
        return global_max


你可能感兴趣的:(Algorithm,LeetCode)