leetcode 152
思路:dp
代码:
class Solution {
public:
int maxProduct(vector& nums) {
int n = nums.size();
int ans = nums[0], Max = nums[0], Min = nums[0];
for(int i = 1; i < n; i++){
int tmp1 = Max*nums[i], tmp2 = Min*nums[i];
Max = max(nums[i], max(tmp1, tmp2));
Min = min(nums[i], min(tmp1, tmp2));
ans = max(ans, Max);
}
return ans;
}
};
int main(){
Solution s;
int a[10005] = {0,-1,4,-4,5,-2,-1,-1,-2,-3,0,-3,0,1,-1,-4,4,6,2,3,0,-5,2,1,-4,-2,-1,3,-4,-6,0,2,2,-1,-5,1,1,5,-6,2,1,-3,-6,-6,-3,4,0,-2,0,2};
vector v(a, a+50);
int ans = s.maxProduct(v);
cout<
如果还需要输出这个序列的下标:
class Solution {
public:
int maxProduct(vector& nums) {
int n = nums.size();
int Max=nums[0], Min=nums[0], l = 0, r = 0, Max_l = 0, Max_r = 0, Min_l = 0, Min_r = 0, ans = nums[0];
for(int i = 1; i < n; i++){
int tmp1 = Max * nums[i];
int tmp2 = Min * nums[i];
int tmp_max_l = Max_l, tmp_max_r = Max_r;
if(nums[i] >= tmp1 && nums[i] >= tmp2){
Max = nums[i];
Max_l = Max_r = i;
}else if(tmp1 >= nums[i] && tmp1 >= tmp2){
Max = tmp1;
Max_r = i;
}else{
Max = tmp2;
Max_l = Min_l;
Max_r = i;
}
if(nums[i] <= tmp1 && nums[i] <= tmp2){
Min = nums[i];
Min_l = Min_r = i;
}else if(tmp1 <= nums[i] && tmp1 <= tmp2){
Min = tmp1;
Min_l = tmp_max_l;
Min_r = i;
}else{
Min = tmp2;
Min_r = i;
}
if(ans < Max){
ans = Max;
l = Max_l;
r = Max_r;
}
}
cout<