Maximum Product of Three Numbers
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3]
Output: 6
Example 2:
Input: [1,2,3,4]
Output: 24
Note:
The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
Multiplication of any three numbers in the input won’t exceed the range of 32-bit signed integer.
C语言
int maximumProduct(int* nums, int numsSize){
if(numsSize==3) return(nums[0]*nums[1]*nums[2]);
int i=0,sec=0,third=0,max=0,min=0,min2=0;
while(i<numsSize){
if(nums[i]>max){third=sec;sec=max;max=nums[i];}
else if(nums[i]>sec){third=sec;sec=nums[i];}
else if(nums[i]>third){third=nums[i];}
if(nums[i]<min){min2=min;min=nums[i];}
else if(nums[i]<min2){min2=nums[i];}
i++;
}
if(min*min2>sec*third){return max*min*min2;}
else{return max*sec*third;}
}
Success
Details
Runtime: 36 ms, faster than 40.78% of C online submissions for Maximum Product of Three Numbers.
Memory Usage: 8.4 MB, less than 100.00% of C online submissions for Maximum Product of Three Numbers.
python3
import heapq
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
a=heapq.nlargest(3, nums)
b=heapq.nsmallest(2, nums)
return max(a[0]*a[1]*a[2], b[0]*b[1]*a[0])
Success
Details
Runtime: 64 ms, faster than 97.58% of Python3 online submissions for Maximum Product of Three Numbers.
Memory Usage: 14.1 MB, less than 5.05% of Python3 online submissions for Maximum Product of Three Numbers.
Maximum Average Subarray I
Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.
Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Note:
1 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].
C语言
double findMaxAverage(int* nums, int numsSize, int k){
int sumMax=0;
int sum=0;
for(int i=0;i<k;i++)
{
sumMax=sumMax+nums[i];
}
sum=sumMax;
for(int i=k;i<numsSize;i++)
{
sum=sum+nums[i]-nums[i-k];
if(sum>sumMax)
{sumMax=sum;}
}
return (double)sumMax/k;
}
Success
Details
Runtime: 176 ms, faster than 15.94% of C online submissions for Maximum Average Subarray I.
Memory Usage: 11.7 MB, less than 100.00% of C online submissions for Maximum Average Subarray I.
python3
sliding window,滑动窗口算法
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
knumSum = sum(nums[:k])
maxavg = knumSum/k
for i in range(1, len(nums) - k + 1):
knumSum = knumSum - nums[i-1] + nums[k+i-1]
avg = knumSum/k
if avg > maxavg:
maxavg = avg
return maxavg
Success
Details
Runtime: 176 ms, faster than 68.28% of Python3 online submissions for Maximum Average Subarray I.
Memory Usage: 15.2 MB, less than 6.25% of Python3 online submissions for Maximum Average Subarray I.