Skip to content

Commit b870a9c

Browse files
solves #2614: PrimeInDiagonal in java
1 parent 75382b2 commit b870a9c

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -812,7 +812,7 @@
812812
| 2600 | [K Items With the Maximum Sum](https://leetcode.com/problems/k-items-with-the-maximum-sum) | [![Java](assets/java.png)](src/KItemsWithTheMaximumSum.java) | |
813813
| 2605 | [Form Smallest Number From Two Digit Arrays](https://leetcode.com/problems/form-smallest-number-from-two-digit-arrays) | [![Java](assets/java.png)](src/FormSmallestNumberFromTwoDigitArrays.java) | |
814814
| 2609 | [Find the Longest Balanced Substring of a Binary String](https://leetcode.com/problems/find-the-longest-balanced-substring-of-a-binary-string) | [![Java](assets/java.png)](src/FindTheLongestBalancedSubstringOfABinaryString.java) | |
815-
| 2614 | [Prime In Diagonal](https://leetcode.com/problems/prime-in-diagonal) | | |
815+
| 2614 | [Prime In Diagonal](https://leetcode.com/problems/prime-in-diagonal) | [![Java](assets/java.png)](src/PrimeInDiagonal.java) | |
816816
| 2639 | [Find the Width of Columns of a Grid](https://leetcode.com/problems/find-the-width-of-columns-of-a-grid) | | |
817817
| 2643 | [Row With Maximum Ones](https://leetcode.com/problems/row-with-maximum-ones) | | |
818818
| 2644 | [Find the Maximum Divisibility Score](https://leetcode.com/problems/find-the-maximum-divisibility-score) | | |

src/PrimeInDiagonal.java

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// https://leetcode.com/problems/prime-in-diagonal
2+
// m: number of rows in matrix
3+
// n: size of numbers in matrix
4+
// T: O(m * sqrt(n))
5+
// S: O(1)
6+
7+
public class PrimeInDiagonal {
8+
public int diagonalPrime(int[][] nums) {
9+
final int rows = nums.length;
10+
int maxPrime = 0;
11+
// left to right diagonal
12+
for (int row = 0 ; row < rows ; row++) {
13+
if (row % 2 == 1 && row == rows / 2) {
14+
continue;
15+
}
16+
if (isPrime(nums[row][row])) {
17+
maxPrime = Math.max(maxPrime, nums[row][row]);
18+
}
19+
}
20+
21+
// top right to bottom left diagonal
22+
for (int row = 0 ; row < rows ; row++) {
23+
if (isPrime(nums[row][rows - row - 1])) {
24+
maxPrime = Math.max(maxPrime, nums[row][rows - row - 1]);
25+
}
26+
}
27+
return maxPrime;
28+
}
29+
30+
private boolean isPrime(int x) {
31+
if (x <= 1) return false;
32+
for (int i = 2 ; i * i <= x ; i++) {
33+
if (x % i == 0) return false;
34+
}
35+
return true;
36+
}
37+
}

0 commit comments

Comments
 (0)