1. 程式人生 > 資訊 >何小鵬:小鵬汽車有超 20% 的使用者付費探索 NGP 自動駕駛輔助系統

何小鵬:小鵬汽車有超 20% 的使用者付費探索 NGP 自動駕駛輔助系統

技術標籤:JAVAleetcodeleetcode演算法

題目描述:

給你一個數組 prices ,其中 prices[i] 是商店裡第 i 件商品的價格。商店裡正在進行促銷活動,如果你要買第 i 件商品,那麼你可以得到與 prices[j] 相等的折扣,其中 j 是滿足 j > i 且 prices[j] <= prices[i] 的 最小下標 ,如果沒有滿足條件的 j ,你將沒有任何折扣。
請你返回一個數組,陣列中第 i 個元素是折扣後你購買商品 i 最終需要支付的價格。

提示:
1 <= prices.length <= 500
1 <= prices[i] <= 10^3

示例 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]

程式碼如下:

class Solution {
    public int[] finalPrices(int[] prices) {
        int n = prices.length;
        int[] arr = new int[n];
        int k = 0;
        boolean flag = true;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n;
j++) { if (prices[i] >= prices[j]) { arr[k] = prices[i] - prices[j]; k++; flag = false; break; } } if (flag) { arr[k] = prices[i]; k++; } flag = true; } return arr; } }

執行結果:
在這裡插入圖片描述