Advertisement
Guest User

MinimumAmount

a guest
Sep 26th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 KB | None | 0 0
  1.     static int calculate_amount(int[] prices){
  2.         int totalAmount = 0;
  3.  
  4.         //empty array, nothing to buy
  5.         if(prices.length < 1){
  6.             return totalAmount;
  7.         }
  8.  
  9.  
  10.         int minPrice = prices[0];
  11.         totalAmount += prices[0];
  12.  
  13.         for (int i = 1; i < prices.length; i++) {
  14.             //get the value of the item with the discount
  15.             int currentPrice = prices[i] - minPrice;
  16.  
  17.             //if the min price is bigger than current price, get the item for free
  18.             if(currentPrice < 0){
  19.                 currentPrice = 0;
  20.             }
  21.  
  22.             //ad it to the total amount
  23.             totalAmount += currentPrice;
  24.  
  25.             // get current price if it is lower than previous min
  26.             minPrice = minPrice > prices[i] ? prices[i] : minPrice;
  27.         }
  28.  
  29.         return totalAmount;
  30.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement