[translate by ChatGPT] I finally joined the weekly contest again today. Previously, I think I only managed to solve all four problems once. This time I thought I should at least be able to solve two within the time limit, but maybe because I hadn’t practiced for a while and wasn’t as familiar, I ended up only getting the second problem correct.

Actually, my ideas for the first and third problems were correct. I just didn’t pay enough attention to some details, or I didn’t handle them carefully, which caused me to waste a lot of time.

When I first read this problem, I thought it was very complicated. I kept thinking that gcd and lcm might require some complex handling, and I didn’t realize you could really solve it just by using these two functions. In fact, I hadn’t used these functions before, so they didn’t immediately come to mind.

After reviewing with ChatGPT’s, I realized that I was close to the correct solution. There were two differences at the time. One was that the lcm part wasn’t implemented as a function but calculated directly by multiplication (this is not necessary). The other was that the variable prod could become very large. When I noticed that, I assumed the approach wouldn’t work and gave up.

After the contest ended, I saw other people’s solutions and realized that because the problem restricts the values and the number of elements in nums, the maximum product is simply the product of numbers from 1 to 9. So once the multiplication exceeds that bound, we can stop checking further.

This taught me that when I see potentially huge numbers, I should check whether there’s actually a built-in upper bound.

Code

class Solution {
public:
    int maxLength(vector<int>& nums) {
        int n = nums.size();
        int maxLen = 1;

        for(int i = 0 ; i < n ; ++i) {
            int l = nums[i];
            int g = nums[i];
            long long prod = nums[i];
            for(int j = i+1 ; j < n ; ++j) {
                l = lcm(l, nums[j]);
                g = gcd(g, nums[j]);
                prod *= nums[j];
                if(prod > 10'000'000'000L) break;
                if(l*g == prod) maxLen = max(maxLen, j-i+1);
            }
        }

        return maxLen;
    }
};