回轉(zhuǎn)壽司

?壽司店周年慶,正在舉辦優(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] + " ");
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容