// 9^{13} = 2541865828329 classSolution { public: ll maxStrength(vector<int>& nums){ ll m = nums[0], M = m; for (int i = 1; i < nums.size(); i++) { ll newm = min({m, (ll)nums[i], m * nums[i], M * nums[i]}); ll newM = max({M, (ll)nums[i], m * nums[i], M * nums[i]}); m = newm, M = newM; } return M; } };
Python
1 2 3 4 5 6 7 8 9
from typing importList
classSolution: defmaxStrength(self, nums: List[int]) -> int: M, m = nums[0], nums[0] for i inrange(1, len(nums)): M, m = max(M, nums[i], M * nums[i], m * nums[i]), \ min(m, nums[i], M * nums[i], m * nums[i]) return M
Java
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { publiclongmaxStrength(int[] nums) { longm= nums[0], M = nums[0]; for (inti=1; i < nums.length; i++) { longnewm= Math.min(m, Math.min((long)(nums[i]), Math.min(m * nums[i], M * nums[i]))); longnewM= Math.max(M, Math.max((long)(nums[i]), Math.max(m * nums[i], M * nums[i]))); m = newm; M = newM; } return M; } }
funcmin(a int64, b int64)int64 { if a < b { return a } return b }
funcmin4(a int64, b int64, c int64, d int64)int64 { return min(a, min(b, min(c, d))) }
funcmax(a int64, b int64)int64 { if a > b { return a } return b }
funcmax4(a int64, b int64, c int64, d int64)int64 { return max(a, max(b, max(c, d))) }
funcmaxStrength(nums []int)int64 { m, M := (int64)(nums[0]), int64(nums[0]) for i := 1; i < len(nums); i++ { m, M = min4(m, (int64)(nums[i]), m * (int64)(nums[i]), M * (int64)(nums[i])), max4(M, (int64)(nums[i]), m * (int64)(nums[i]), M * (int64)(nums[i])) } return M }