?壽司店周年慶,正在舉辦優(yōu)惠活動回饋新老客戶壽司轉(zhuǎn)盤上總共有n盤壽司,prices[i] 是第 i 盤壽司的價格,如果客戶選擇了第 i盤壽司,壽司店免費(fèi)贈送客戶距離第 i 盤壽司最近的下一盤壽司 j,前提是prices[j] < prices[i],如果沒有滿足條件的 j,則不贈送壽司。
?每個價格的壽司都可無限供應(yīng)。
?輸入描述:輸入的每一個數(shù)字代表每盤壽司的價格,每盤壽司的價格之間使用空格分隔;壽司的盤數(shù) n范圍為: 1 <= n <= 500
?輸出描述:輸出享受優(yōu)惠后的一組數(shù)據(jù),每個值表示客戶選擇第 i 盤壽司時實(shí)際得到的壽司的總價格。使用空格進(jìn)行分隔。
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] pricestring = sc.nextLine().trim().split("[ ]");
int[] prices = new int[pricestring.length];
for(int i = 0;i < prices.length;i++){
prices[i] = Integer.parseInt(pricestring[i]);
}
//單調(diào)棧
Deque<Integer> price = new ArrayDeque<>();
//記錄結(jié)果數(shù)組
int[] res = Arrays.copyOf(prices,prices.length);
for(int i = 0;i < res.length;i++){
//送小的,所以右邊比左邊大或等入棧
while(!price.isEmpty()&&prices[price.peek()] > prices[i]){
int index = price.pop();
res[index] = prices[index] + prices[i];
}
price.push(i);
}
//后半部分沒找到的,需要從前面尋找
while(!price.isEmpty()){
int index = price.pop();
for(int i = 0;i < index;i++){
if(prices[index] > prices[i]){
res[index] = prices[index] + prices[i];
break;
}
}
}
for(int i = 0;i < res.length;i++){
System.out.print(res[i] + " ");
}
}
}