Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 6a957a4

Browse files
committed
Code Optimization: Have implemented the program to find the last stone weight.
1 parent 9a78dcf commit 6a957a4

File tree

2 files changed

+37
-34
lines changed

2 files changed

+37
-34
lines changed

.idea/workspace.xml

Lines changed: 28 additions & 27 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/com/raj/LastStoneWeight.java

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
package com.raj;
3333

3434
import java.util.ArrayList;
35-
import java.util.Collections;
35+
import java.util.Comparator;
3636

3737
public class LastStoneWeight {
3838
public static void main(String[] args) {
@@ -47,12 +47,14 @@ public static void main(String[] args) {
4747

4848
// Logic.
4949
while (ans.size() >= 2) {
50-
Collections.sort(ans);
51-
int lastChar = ans.get(ans.size() - 1);
52-
int secondLastChar = ans.get(ans.size() - 2);
53-
int val = Math.abs(lastChar - secondLastChar);
54-
ans.remove(ans.size() - 1);
55-
ans.set(ans.size() - 1, val);
50+
// Sort the ArrayList in descending order.
51+
ans.sort(Comparator.reverseOrder());
52+
int firstVal = ans.get(0);
53+
int secondVal = ans.get(1);
54+
// Get the positive difference.
55+
int val = Math.abs(firstVal - secondVal);
56+
ans.remove(0);
57+
ans.set(0, val);
5658
}
5759

5860
// Display the result.

0 commit comments

Comments
 (0)