4.Math
1.Integer Break
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
Note: You may assume that n is not less than 2 and not larger than 58.
利用求导来分析,分析结果得到大部分情况应该按3切分,如果n>=5,那么果断都应该按3切分,如果n<5,作为特殊情况来考虑(比如4就应该拆分成2*2,而不是3*1)。
public class Solution {
public int integerBreak(int n) {
//特殊情况
if(n==2){
return 1;
}
if(n==3){
return 2;
}
int product=1;
while(n>=5){
product = product*3;
n=n-3;
}
product = product*n;
return product;
}
}
2.Self Crossing
参考Java Oms with explanation实现:
public class Solution {
/* i-2
case 1 : i-1┌─┐
└─┼─>i
i-3
i-2
case 2 : i-1 ┌────┐
└─══>┘i-3
i i-4 (i overlapped i-4)
case 3 : i-4
┌──┐
│i<┼─┐
i-3│ i-5│i-1
└────┘
i-2
*/
//只有上述四种情况之一
public boolean isSelfCrossing(int[] num) {
int length = num.length;
if(length<=3){
return false;
}
for (int i = 3; i < length; i++) {
//case 1
if(num[i-1]<=num[i-3]&&num[i]>=num[i-2]){
return true;
}
//case 2
if(i>=4){
if(num[i-1]==num[i-3]&&num[i]+num[i-4]>=num[i-2]){
return true;
}
}
//case 3
if(i>=5){
if(num[i]+num[i-4]>=num[i-2]&&num[i-1]+num[i-5]>=num[i-3]&&num[i-1]<=num[i-3]&&num[i-2]>num[i-4]){
return true;
}
}
}
return false;
}
}