classSolution: defmaxProduct(self, nums: List[int]) -> int: a, b = nums[0], nums[1] if a < b: a, b = b, a for i inrange(2, len(nums)): num = nums[i] if num > a: a, b = num, a elif num > b: b = num return (a - 1) * (b - 1)
[sol2-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intmaxProduct(vector<int>& nums){ int a = nums[0], b = nums[1]; if (a < b) { swap(a, b); } for (int i = 2; i < nums.size(); i++) { if (nums[i] > a) { b = a; a = nums[i]; } elseif (nums[i] > b) { b = nums[i]; } } return (a - 1) * (b - 1); } };
[sol2-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { publicintmaxProduct(int[] nums) { inta= nums[0], b = nums[1]; if (a < b) { inttemp= a; a = b; b = temp; } for (inti=2; i < nums.length; i++) { if (nums[i] > a) { b = a; a = nums[i]; } elseif (nums[i] > b) { b = nums[i]; } } return (a - 1) * (b - 1); } }
[sol2-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassSolution { publicintMaxProduct(int[] nums) { int a = nums[0], b = nums[1]; if (a < b) { int temp = a; a = b; b = temp; } for (int i = 2; i < nums.Length; i++) { if (nums[i] > a) { b = a; a = nums[i]; } elseif (nums[i] > b) { b = nums[i]; } } return (a - 1) * (b - 1); } }
[sol2-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
intmaxProduct(int* nums, int numsSize){ int a = nums[0], b = nums[1]; if (a < b) { int c = a; a = b; b = c; } for (int i = 2; i < numsSize; i++) { if (nums[i] > a) { b = a; a = nums[i]; } elseif (nums[i] > b) { b = nums[i]; } } return (a - 1) * (b - 1); }
[sol2-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var maxProduct = function(nums) { let a = nums[0], b = nums[1]; if (a < b) { const temp = a; a = b; b = temp; } for (let i = 2; i < nums.length; i++) { if (nums[i] > a) { b = a; a = nums[i]; } elseif (nums[i] > b) { b = nums[i]; } } return (a - 1) * (b - 1); };
[sol2-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funcmaxProduct(nums []int)int { a, b := nums[0], nums[1] if a < b { a, b = b, a } for _, num := range nums[2:] { if num > a { a, b = num, a } elseif num > b { b = num } } return (a - 1) * (b - 1) }