Maximum Product Subarray

May 28, 2017


leetcode 152

# -*- coding: utf-8 -*-
# @Author: zinber
# @Date:   2017-05-28 15:00:53
# @Last Modified by:   zinber
# @Last Modified time: 2017-05-28 16:06:04

def product(nums):
    max_number=nums[0]
    first_number=0
    last_number =0
    neg_numbers = 0
    pos_numbers = 0
    calc_num = 0
    for v in nums:
        if v == 0:
            if neg_numbers % 2 != 0:
                n = 0
                if last_number == 0:
                    n = first_number
                else:
                    n = max(first_number,last_number)
                if pos_numbers > 0:
                    calc_num = calc_num / n
                if calc_num < n and n != 0:
                    calc_num = calc_num / n
            if max_number < calc_num:
                    max_number = calc_num
            if max_number < 0:
                max_number = 0
            first_number=0
            last_number =0
            neg_numbers = 0
            pos_numbers = 0
            calc_num = 0
        else:
            if calc_num == 0:
                calc_num = 1
            calc_num = calc_num * v
            if v < 0 :
                if first_number == 0:
                    first_number = calc_num
                last_number = v
                neg_numbers = neg_numbers + 1
            else:
                pos_numbers = pos_numbers + 1
                if last_number != 0:
                    last_number = last_number * v

    if neg_numbers % 2 != 0:
        n = 0
        if last_number == 0:
            n = first_number
        else:
            n = max(first_number,last_number)
        if pos_numbers > 0:
            calc_num = calc_num / n
        if calc_num < n and n !=0:
            calc_num = calc_num / n
    if max_number < calc_num:
        max_number = calc_num
    print(max_number)
product([-3,0,1,-1])