题目
解答
public class Solution {public int maxProduct(int[] nums) {if (nums == null || nums.length == 0) {return 0;}if (nums.length == 1) {return nums[0];}int max = nums[0];int min = nums[0];int res = nums[0];for (int i = 1; i < nums.length; i++) {int tmp = max;max = Math.max(nums[i], Math.max(nums[i] * max, nums[i] * min));min = Math.min(nums[i], Math.min(nums[i] * tmp, nums[i] * min));res = Math.max(res, max);}return res;}
}
要点
求解乘积的最大子序列时,需要关注正、负号对结果的影响,关注点有:
- 子序列中包含0,则乘积值为0。
- 子序列中的没有负数,或者负数的个数为偶数,则最大值即是所有值的乘积。
- 子序列中包含负数,并且负数的个数为奇数,则求解本子序列的最大乘积时,不能包含全部元素。
因此在求解过程中,不能只记录最大值,需要同时记录最小值。
设计用例时,对照上述关注点,可以输出如下用例:
@Before
public void before() {t = new Solution();
}@Test
public void test001() {assertEquals(6, t.maxProduct(new int[] { 2, 3, -2, 4 }));
}@Test
public void test001001() {assertEquals(24, t.maxProduct(new int[] { -2, 2, 3, 4 }));
}@Test
public void test001002() {assertEquals(12, t.maxProduct(new int[] { -2, 2, 0, 3, 4 }));
}@Test
public void test001003() {assertEquals(4, t.maxProduct(new int[] { -2, 2, 0, 3, 0, 4 }));
}@Test
public void test002() {assertEquals(0, t.maxProduct(new int[] { -2, 0, -1 }));
}@Test
public void test003() {assertEquals(24, t.maxProduct(new int[] { -2, 3, -4 }));
}@Test
public void test003001() {assertEquals(24, t.maxProduct(new int[] { 0, -2, 3, -4 }));
}@Test
public void test003002() {assertEquals(3, t.maxProduct(new int[] { -2, 0, 3, -4 }));
}@Test
public void test003003() {assertEquals(12, t.maxProduct(new int[] { -2, -3, -4 }));
}@Test
public void test003004() {assertEquals(24, t.maxProduct(new int[] { -2, -3, 4 }));
}@Test
public void test003005() {assertEquals(12, t.maxProduct(new int[] { -2, 0, -3, -4 }));
}