LeetCode in Kotlin

3546. Equal Sum Grid Partition I

Medium

You are given an m x n matrix grid of positive integers. Your task is to determine if it is possible to make either one horizontal or one vertical cut on the grid such that:

Return true if such a partition exists; otherwise return false.

Example 1:

Input: grid = [[1,4],[2,3]]

Output: true

Explanation:

A horizontal cut between row 0 and row 1 results in two non-empty sections, each with a sum of 5. Thus, the answer is true.

Example 2:

Input: grid = [[1,3],[2,4]]

Output: false

Explanation:

No horizontal or vertical cut results in two non-empty sections with equal sums. Thus, the answer is false.

Constraints:

Solution

class Solution {
    fun canPartitionGrid(grid: Array<IntArray>): Boolean {
        val n = grid.size
        val m = grid[0].size
        var totalRowSum = 0L
        val prefixRowWise = LongArray(n)
        val prefixColWise = LongArray(m)
        for (i in 0..<n) {
            for (j in 0..<m) {
                val v = grid[i][j]
                prefixRowWise[i] += v.toLong()
                prefixColWise[j] += v.toLong()
            }
        }
        for (r in prefixRowWise) {
            totalRowSum += r
        }
        val totalColSum: Long = totalRowSum
        var currentRowUpperSum = 0L
        for (i in 0..<n - 1) {
            currentRowUpperSum += prefixRowWise[i]
            val lowerSegmentSum = totalRowSum - currentRowUpperSum
            if (currentRowUpperSum == lowerSegmentSum) {
                return true
            }
        }
        var currentColLeftSum = 0L
        for (j in 0..<m - 1) {
            currentColLeftSum += prefixColWise[j]
            val rightSegmentSum = totalColSum - currentColLeftSum
            if (currentColLeftSum == rightSegmentSum) {
                return true
            }
        }
        return false
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy