Eating apples

You are staying at point (1, 1) in a matrix 109×109. You can travel by following these steps:

  1. If the row where you are staying has 1 or more apples, then you can go to another end of the row and can go up.
  2. Otherwise, you can go up.

The matrix contains N apples. The ith Apple is at a point (xi, yi). You can eat these apples while traveling. 

For each of the apples, your task is to determine the number of apples that have been eaten before.

Example:

Input: 5
1 4
6 7
2 3
2 5
3 7
Output: 0 4 2 1 3

Approach

Java

import java.util.Arrays;

public class EatingApples {
    public static void main(String[] args) {

        int n = 5;
        EatingApples.Cell[] cells = new EatingApples.Cell[n];
        int arr[][] = { { 14 }, { 67 }, { 23 }, { 25 }, { 37 } };
        for (int i = 0; i < n; i++) {
            cells[i] = new EatingApples.Cell(arr[i][0], arr[i][1], i, 0);
        }

        Arrays.sort(cells);
        boolean rightDirection = true;
        int lastEaten = -1;
        for (int i = 0; i < n; i++) {
            int j = i;
            if (rightDirection) {
                while (j < n && cells[j].i == cells[i].i) {
                    cells[j].previouslyEaten = lastEaten;
                    cells[j].previouslyEaten++;
                    lastEaten = cells[j].previouslyEaten;
                    j++;
                }
                i = j - 1;
            } else {
                while (j < n - 1 && cells[j + 1].i == cells[i].i) {
                    j++;
                }
                for (int k = j; k >= i; k--) {
                    cells[k].previouslyEaten = lastEaten;
                    cells[k].previouslyEaten++;
                    lastEaten = cells[k].previouslyEaten;
                }
                i = j;
            }

            rightDirection = !rightDirection;
        }

        int[] result = new int[n];
        for (EatingApples.Cell cell : cells) {
            result[cell.index] = cell.previouslyEaten;
        }

        for (int r : result) {
            System.out.println(r);
        }
    }

    private static class Cell implements Comparable<EatingApples.Cell> {

        public int i;
        public int j;
        public int index;
        public int previouslyEaten;

        public Cell(int iint jint indexint previouslyEaten) {
            this.i = i;
            this.j = j;
            this.index = index;
            this.previouslyEaten = previouslyEaten;
        }

        public int compareTo(EatingApples.Cell o) {
            if (this.i != o.i) {
                return this.i - o.i;
            }
            return this.j - o.j;
        }

    }
}


No comments:

Post a Comment