javaarraysfor-loop

Calculate sum of array's prices included within range


I have the following task, write a method that takes a list of prices and sums them up, including only those that are greater than minPrice (inclusive) and less than maxPrice (inclusive), and returns the amount.

Only for loop can be used.

And I have a wrong result in return.

I presume that I have a mistake in if (price >= minPrice && price <= maxPrice) counter++;

But I do not understand why.

    public int getPricesSum(int[] prices, int minPrice, int maxPrice) {
        
        if (prices.length == 0) return 0;
        
        int counter = 0;
        
        for(int i = 0; i < prices.length; i++) {
            int price = prices[i];
            if (price >= minPrice && price <= maxPrice) counter++;
        }
        
        int result [] = new int [counter];
        
        int newResult = 0;
        
        for(int i = 0; i < result.length; i++) {
            newResult += prices[i];
        }
        
        return newResult;
        
    }

    public static void main(String[] args) {
        QuadraticEquationSolver shop = new QuadraticEquationSolver();

        //Should be 144 - 20 + 50 + 40 + 34
        int[] prices = new int[] {10, 20, 50, 40, 34, 500};
        System.out.println(shop.getPricesSum(prices, 20, 50));
    }
  }

The result is 120. I suppose it calculates only the first four indexes of the array.


Solution

  • Your task is to determine the sum of prices within the given range [minPrice, maxPrice]. Counting or copying the elements to a new array is not necessary to achieve your goal.

    You could break down your problem into three steps:

    public int getPricesSum(int[] prices, int minPrice, int maxPrice) {
        int newResult = 0;    
        for(int i = 0; i < prices.length; i++) {
            if (prices[i] >= minPrice && prices[i] <= maxPrice){
                newResult += prices[i];
            }
        }
        return newResult;
    }
    
    public static void main(String[] args) {
        QuadraticEquationSolver shop = new QuadraticEquationSolver();
        int[] prices = new int[] {10, 20, 50, 40, 34, 500};
        System.out.println(shop.getPricesSum(prices, 20, 50));
    }