Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights
x
and y
with x <= y
. The result of this smash is:- If
x == y
, both stones are totally destroyed;
- If
x != y
, the stone of weightx
is totally destroyed, and the stone of weighty
has new weighty-x
.
Example:
Input: stones[]={2,7,4,1,8,1}
Output: 1
Approach
Java
import java.util.PriorityQueue;public class LastStoneWeight {public static void main(String[] args) {int stones[] = { 2, 7, 4, 1, 8, 1 };System.out.println(lastStoneWeight(stones));}// function to find the last stone weightprivate static int lastStoneWeight(int[] stones) {// make desc priority queue of all stonesPriorityQueue<Integer> q = new PriorityQueue<Integer>((x, y) -> y - x);for (int i = 0; i < stones.length; i++) {q.add(stones[i]);}// iterate till the priority queue size is// greater than 1while (q.size() > 1) {// pop top 2 elementsint x = q.poll();int y = q.poll();// push the absolute value diff// of both the elementsq.add(Math.abs(x - y));}// return the top of// priority queuereturn q.peek();}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the last stone//weightint lastStoneWeight(vector<int>& stones){//make priority queue of all stonespriority_queue <int> q(stones.begin(), stones.end());//iterate till the priority queue size is//greater than 1while(q.size()>1){//pop top 2 elementsint x = q.top();q.pop();int y = q.top();q.pop();//push the absoulute value diff//of both the elementsq.push(abs(x-y));}//return the top of//priority queuereturn q.top();}int main(){vector<int> stones={2,7,4,1,8,1};cout<<lastStoneWeight(stones);return 0;}
No comments:
Post a Comment