Lc5424_數組中兩元素的最大乘積

package com.example.demo; /** * 5424. 數組中兩元素的最大乘積 顯示英文描述 * 通過的用戶數 219 * 嘗試過的用戶數 244 * 用戶總通過次數 230 * 用戶總提交次數 261 * 題目難度 Easy * 給你一個整數數組 nums,請你選擇數組的兩個不同下標 i 和 j,使 (nums[i]-1)*(nums[j]-1) 取得最大值。 * <p> * 請你計算並返回該式的最大值。 * <p> * <p> * <p> * 示例 1: * <p> * 輸入:nums = [3,4,5,2] * 輸出:12 * 解釋:如果選擇下標 i=1 和 j=2(下標從 0 開始),則可以獲得最大值,(nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12 。 * 示例 2: * <p> * 輸入:nums = [1,5,4,5] * 輸出:16 * 解釋:選擇下標 i=1 和 j=3(下標從 0 開始),則可以獲得最大值 (5-1)*(5-1) = 16 。 * 示例 3: * <p> * 輸入:nums = [3,7] * 輸出:12 * <p> * <p> * 提示: * <p> * 2 <= nums.length <= 500 * 1 <= nums[i] <= 10^3 */ public class Lc5424 { /** * 注意可能第一大和第二大都是同一個數字 * * @param nums * @return */ public static int maxProduct(int[] nums) { int maxIndex = 0; int max = nums[0]; int secMax = nums[1]; for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { secMax = max; max = nums[i]; maxIndex = i; } else if (nums[i] <= max && maxIndex != i && nums[i] > secMax) { secMax = nums[i]; } } return (max - 1) * (secMax - 1); } public static void main(String[] args) { // int[] nums = {3,4,5,2}; int[] nums = {1, 5, 4, 5}; // int[] nums = {10,2,5,2}; System.out.println(maxProduct(nums)); } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章