LeetCode 152. Maximum Product Subarray

本文介绍了一种寻找数组中具有最大乘积的连续子数组的方法,并给出了解决方案。此外,还讨论了通过翻转特定位段来最大化给定整数的位数的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


Keep three pointers, one always points to current minimum number, one always points to current maximum number, one keeps on updating max result.

int maximumProduct(vector<int>& nums) {
  int positive_max_so_far = 1;
  int negative_min_so_far = 1;
  int maxProduct = INT_MIN;
  for(int i = 0; i < nums.size(); ++i) {
    if(nums[i] == 0) {
      positive_max_so_far = 1;
      negative_min_so_far = 1;
    } else if(nums[i] > 0) {
      positive_max_so_far = positive_max_so_far * nums[i];
      negative_min_so_far = min(negative_min_so_far, min(negative_min_so_far * nums[i], 1));
    } else {
      int tmp = negative_min_so_far;
      negative_min_so_far = min(positive_max_so_far * nums[i], 1);
      positive_max_so_far = max(tmp * nums[i], 1);
    }
    maxProduct = max(maxProduct, positive_max_so_far);
  }
  return maxProduct;
}


int main(void) {
  vector<int> nums{-1, 2, 3, -2};
  cout << maximumProduct(nums) << endl;
}


To summarize the algorithm, this is using Kadane's algorithm, optimized local --> optimized global.

1: Given an array of integer, Find the maximum sum subsequence such that elements are not consecutive. 

For example: A[-2, 1, -3, 4, -1, 2, -5, 4], then max sum = 11 with the subarray [1, 4, 2, 4]

To use local optimized result to get optimized global results. In this function, we need to maintain two variables: contains(i), exclude(i)

int getMaxSum(vector<int>& nums) {
  int n = nums.size();
  vector<int> max_include(n, 0);
  vector<int> max_exclude(n, 0);
  max_include[0] = nums[0];
  max_exclude[0] = INT_MIN;
  int maxSum = nums[0];
  for(int i = 1; i < nums.size(); ++i) {
    max_include[i] = max(max_exclude[i-1] + nums[i], nums[i]);
    max_exclude[i] = max(max_include[i-1], max_exclude[i-1]);
    maxSum = max(max_include[i], max_exclude[i]);
  }
  return maxSum;
}

int main(void) {
  vector<int> nums {-2, 1, -3, 4, -1, 2, 1, -5, 4};
  cout << getMaxSum(nums) << endl;
}


2: Given an integer N, find maximum number of set bits after flipping a single contagious segment of bits (bits from L to R index)

Constraints: 1 <= N <= 2 ^ 100000, 0 <= L <= R < logN, Sample Input : 146, Sample output: 6

146 can be represented as 1 0 0 1 0 0 1 0, we can get a maximum of 6 ones in the given binary array by performing the following single segment bit flip operation:

Flip [1, 5] ==> 1 1 1 0 1 1 1 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值