搜索此博客

2011年2月25日星期五

Given an array of numbers, return maximum products of all possible n-1 numbers

Solution 1:

set array[] as initial array;
s[i] represents the product of the first i numbers

s[0] = 1 is the boundary, Thus s[i]=s[i-1]*array[i-1], 1 <= i <= N; t[i] represents the product of the last (N-i) numbers
t[N+1] = 1 is also the boundary;
Thus, t[i]=t[i+1]*array[i],1 <= i <= N;

set p[i] is the product of N-1 numbers except the number i.
p[i]=s[i-1]*t[i+1]

Searching from the begin to the end, we can get the array s[]; Searching from the end to the begin, we can get the array t[]. In the linear time, we can get p[]. The maximum value of p[] is what we need.

Solution2: Support P is the product of total N numbers;
There are three cases:
1) P is 0: That means there is at least one 0 in the array. If we remove one 0, the product of other N-1 numbers is Q.
1.1 Q is 0. That means the array has at least two 0. The product of N-1 numbers is just 0.
1.2 Q > 0. Return Q.
1.3 Q < 0. Return 0.

2) P < 0. We will remove a negative number from the array. To get the biggest product of N-1 number, we had to remove the minimum absolute value during all the negative numbers.

3) P > 0. We will remove the minimum absolute value during all the positive numbers.

没有评论:

发表评论