Sort by

recency

|

390 Discussions

|

  • + 0 comments

    Java:

    public static int minimumLoss(List<Long> price) {
        // Create a sorted copy of the prices list
        List<Long> sorted = new ArrayList<>(price);
        Collections.sort(sorted);
    
        // Map to store the original index of each price
        HashMap<Long, Integer> IndexMap = new HashMap<>();
        for (int i = 0; i < price.size(); i++) {
          IndexMap.put(price.get(i), i);
        }
    
        long minLoss = Long.MAX_VALUE;
    
        // Iterate through the sorted prices to calculate the minimum loss
        for (int i = 0; i < sorted.size() - 1; i++) {
          Long next = sorted.get(i + 1);
          Long current = sorted.get(i);
          // Check if the "next" price comes after the "current" price in the
          // original list
          if (next - current < minLoss
              && IndexMap.get(next) < IndexMap.get(current)) {
            minLoss = next - current;
          }
        }
    
        return (int) minLoss;
      }
    }
    
      }
    }
    
  • + 0 comments

    Python Solution:

    def minimumLoss(price):
        arr = sorted(enumerate(price), key=lambda x: x[1], reverse=True)
        diff = [arr[i][1] - arr[i + 1][1] for i in range(len(arr) - 1) if arr[i][0] < arr[i + 1][0]]
        return max(min(diff), 0)
    
  • + 0 comments

    I think the best way to solve it is to use a BST. Sadly, there's no suitable built-in BST in C# which is my favorite coding language. So, I solved it in C++.

    int minimumLoss(std::vector<long> price) {
    	std::set<long> before;
    	long minLoss = LONG_MAX;
    	for (long p : price)
    	{
    		long nearestGreater = *before.upper_bound(p);
    		long loss = nearestGreater - p;
    		if (loss > 0 && loss < minLoss)
    			minLoss = loss;
    
    		before.insert(p);
    	}
    
    	return minLoss;
    }
    
  • + 0 comments

    I think the best way to solve it is to use a BST. Sadly, there's no suitable built-in BST in C# which is my favorite coding language. So, I solved it in C++.

  • + 0 comments

    do we count 8-3 as well?