Java for LeetCode 152 Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4]
,
the contiguous subarray [2,3]
has the largest product = 6
.
解题思路:
计算连续的积最大,由于会有负数出现,因此需要用两个int表示包含nums[i]的最大值和最小值,然后res=Math.max(res, max)即可,JAVA实现如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public int maxProduct( int [] nums) { if (nums.length== 1 ) return nums[ 0 ]; int max=nums[ 0 ],min=nums[ 0 ],res=nums[ 0 ],maxTemp= 0 ,mintemp= 0 ; for ( int i= 1 ;i<nums.length;i++){ maxTemp=max*nums[i]; mintemp=min*nums[i]; max=Math.max(nums[i],Math.max(maxTemp, mintemp)); min=Math.min(nums[i],Math.min(maxTemp, mintemp)); res=Math.max(res, max); } return res; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步