[Leetcode]152. Maximum Product Subarray @python
2016-02-05 14:30
721 查看
题目
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.
题目要求
给定一个数组,求其一个子数组,使得子数组各个元素的乘积最大。解题思路
此题借鉴了南郭子綦的解题思路。借此题需要考虑的是乘积中的负负得正的技巧。所以需要记录下当前的最小值,因为最小值可能为一个负数,负数再乘以一个负数可能得到一个很大的数。
代码
class Solution(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 min_tmp = nums[0] max_tmp = nums[0] res = nums[0] for i in range(1,len(nums)): a = nums[i] * min_tmp b = nums[i] * max_tmp c = nums[i] min_tmp = min(a,min(b,c)) max_tmp = max(a,max(b,c)) if res < max_tmp: res = max_tmp return res
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解