这个算法比较简单
蛮力算法,就是按照题目的意思,一步一步的走,用时间来换结果
给你一个数组 prices ,其中 prices[i] 是商店里第 i 件商品的价格。
商店里正在进行促销活动,如果你要买第 i 件商品,那么你可以得到与 prices[j] 相等的折扣,其中 j 是满足 j > i 且 prices[j] <= prices[i] 的 最小下标 ,如果没有满足条件的 j ,你将没有任何折扣。
请你返回一个数组,数组中第 i 个元素是折扣后你购买商品 i 最终需要支付的价格。
示例 1:
输入:prices = [8,4,6,2,3]
输出:[4,2,4,2,3]
解释:
商品 0 的价格为 price[0]=8 ,你将得到 prices[1]=4 的折扣,所以最终价格为 8 - 4 = 4 。
商品 1 的价格为 price[1]=4 ,你将得到 prices[3]=2 的折扣,所以最终价格为 4 - 2 = 2 。
商品 2 的价格为 price[2]=6 ,你将得到 prices[3]=2 的折扣,所以最终价格为 6 - 2 = 4 。
商品 3 和 4 都没有折扣。
示例 2:
输入:prices = [1,2,3,4,5]
输出:[1,2,3,4,5]
解释:在这个例子中,所有商品都没有折扣。
示例 3:
输入:prices = [10,1,1,6]
输出:[9,0,1,6]
提示:
1 <= prices.length <= 500
1 <= prices[i] <= 10^3
package nunber2;
//蛮力算法,就是按照题目的意思,一步一步的走,用时间来换结果
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int[] nums= {1,2,3,4,5};
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
if(nums[i]>=nums[j]) {
nums[i]=nums[i]-nums[j];
break;
}
}
}
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]+" ");
}
}
}
小区便利店正在促销,用 numExchange 个空酒瓶可以兑换一瓶新酒。你购入了 numBottles 瓶酒。
如果喝掉了酒瓶中的酒,那么酒瓶就会变成空的。
请你计算 最多 能喝到多少瓶酒。
示例 1:输入:numBottles = 9, numExchange = 3 输出:13 解释:你可以用 3 个空酒瓶兑换 1 瓶酒。
所以最多能喝到 9 + 3 + 1 = 13 瓶酒。 示例 2:输入:numBottles = 15, numExchange = 4 输出:19 解释:你可以用 4 个空酒瓶兑换 1 瓶酒。
所以最多能喝到 15 + 3 + 1 = 19 瓶酒。 示例 3: 输入:numBottles = 5, numExchange = 5
输出:6 示例 4: 输入:numBottles = 2, numExchange = 3 输出:2 提示: 1 <=
numBottles <= 100 2 <= numExchange <= 100
package nunber2;
public class Solution_1518 {
public static void main(String[] args) {
int numBottles=9;
int numExchange=3;
System.out.println(numWaterBottles(numBottles,numExchange));
}
public static int numWaterBottles(int numBottles, int numExchange) {
if( numBottles< numExchange) //如果买的酒很少,直接就可以返回
return numBottles;
else
return numBottles+result( numBottles, numExchange);
}
public static int result(int numBottles, int numExchange) {//返回除数
int curr=numBottles/numExchange;//除数
int num=numBottles%numExchange;
if((curr+num)<numExchange)
return curr;
return curr+result(curr+num,numExchange);
}
}