问题描述
面试的时候问到一道题,题目是这样子的:
一农民有1800个番茄,用马拉到集市上卖,一次只能拉600个,家到集市有600公里,马走一公里吃一个番茄,问最多能卖出多少个番茄
看到这题目下意识的乘减会发现:
1800-600*(1800/600)= 0
不过仔细思考发现,不能考虑这么简单,还要考虑往返,也不可能是0,所以应该是分段计算。
计算过程
1800/600=3
32-1=5
600/5=120
1800-600=1200
1200/600=2
22-1=3
600/3=200
1200-600=600
600-120-200=280
600-280=320
可以得出最佳的结果是320个
Java代码实现
/**
* 一农民有1800个番茄,用马拉到集市上卖,
* 一次只能拉600个,家到集市有600公里,
* 马走一公里吃一个番茄,
* 问最多能卖出多少个番茄
*/
@Test
public void test01(){
//番茄数
int tomato = 1600;
//距离
int distance= 400;
//最大负重
int maxW = 400;
//本次要走多少次
int nowCount = 0;
while (distance > 0){
//计算往返次数
nowCount = tomato/maxW;
if(nowCount==1){
break;
}
//计算一共要走多少次
int count = nowCount * 2 - 1;
//计算本次最优距离
int gd = maxW / count;
distance = distance - gd;
tomato = tomato - count * gd;
}
tomato = tomato - distance;
System.out.println(tomato);
}