- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 66 lines of Java from the credited upstream file 3334.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public long maxScore(int[] nums) {3 final int n = nums.length;4 5 6 long[][] prefix = getPrefix(nums);7 long[] prefixGcd = prefix[0];8 long[] prefixLcm = prefix[1];9 10 11 long[][] suffix = getSuffix(nums);12 long[] suffixGcd = suffix[0];13 long[] suffixLcm = suffix[1];14 long ans = suffixGcd[0] * suffixLcm[0];15 16 for (int i = 0; i < n; ++i) {17 final long gcd1 = i > 0 ? prefixGcd[i - 1] : 0;18 final long gcd2 = i + 1 < n ? suffixGcd[i + 1] : 0;19 final long lcm1 = i > 0 ? prefixLcm[i - 1] : 1;20 final long lcm2 = i + 1 < n ? suffixLcm[i + 1] : 1;21 final long score = gcd(gcd1, gcd2) * lcm(lcm1, lcm2);22 ans = Math.max(ans, score);23 }24 25 return ans;26 }27 28 29 private long[][] getPrefix(int[] nums) {30 long[] prefixGcd = new long[nums.length];31 long[] prefixLcm = new long[nums.length];32 long currGcd = 0;33 long currLcm = 1;34 for (int i = 0; i < nums.length; ++i) {35 currGcd = gcd(currGcd, nums[i]);36 currLcm = lcm(currLcm, nums[i]);37 prefixGcd[i] = currGcd;38 prefixLcm[i] = currLcm;39 }40 return new long[][] {prefixGcd, prefixLcm};41 }42 43 44 private long[][] getSuffix(int[] nums) {45 long[] suffixGcd = new long[nums.length];46 long[] suffixLcm = new long[nums.length];47 long currGcd = 0;48 long currLcm = 1;49 for (int i = nums.length - 1; i >= 0; --i) {50 currGcd = gcd(currGcd, nums[i]);51 currLcm = lcm(currLcm, nums[i]);52 suffixGcd[i] = currGcd;53 suffixLcm[i] = currLcm;54 }55 return new long[][] {suffixGcd, suffixLcm};56 }57 58 private long gcd(long a, long b) {59 return b == 0 ? a : gcd(b, a % b);60 }61 62 private long lcm(long a, long b) {63 return a * (b / gcd(a, b));64 }65}66