# 64. Minimum Path Sum

## Problem

{% embed url="<https://leetcode.com/problems/minimum-path-sum/>" %}

## Intuition

<figure><img src="https://1388126071-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MVQ7Ie-PZpN_8yApX0-%2Fuploads%2FQBVjumneYJJoyrE9iaQz%2Fimage.png?alt=media&#x26;token=27dbdf39-b6f1-46ee-a392-87c734775ecf" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1388126071-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MVQ7Ie-PZpN_8yApX0-%2Fuploads%2FuSJtNAfSdgsk2ByUSjq8%2Fimage.png?alt=media&#x26;token=85242268-5fba-4eaa-8a67-4e49bf3c9943" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1388126071-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MVQ7Ie-PZpN_8yApX0-%2Fuploads%2FiquelpBHmDkT3CcDRJw4%2Fimage.png?alt=media&#x26;token=962ed7f1-b554-4740-af2a-8197414235ed" alt=""><figcaption></figcaption></figure>

## Time Complexity

## Space Complexity

## Solution

```java
class Solution {
    public int minPathSum(int[][] grid) {
        // R -> No. of rows, C -> No. of columns
        // Time Complexity: O(R*C), need to visit all the cells only once
        // Space Complexity: O(1), no extra space is used. 
            // Input only used to store subproblem results

        int R = grid.length; // Number of rows
        int C = grid[0].length; // Number of columns

        // Iterate over each cell in the grid
        for (int row = 0; row < R; row++) {
            for (int col = 0; col < C; col++) {
                if (row == 0 && col == 0) {
                    // Skip the top-left cell since it has no incoming paths
                    continue;
                } else if (row == 0) {
                    // For cells in the first row, only consider the path from the left
                    grid[0][col] += grid[0][col - 1];
                } else if (col == 0) {
                    // For cells in the first column, only consider the path from above
                    grid[row][0] += grid[row - 1][0];
                } else {
                    // For other cells, choose the minimum path from above and from the left,
                    // and add it to the current cell's value
                    int up = grid[row - 1][col];
                    int left = grid[row][col - 1];
                    grid[row][col] += Math.min(up, left);
                }
            }
        }
        return grid[R - 1][C - 1]; // Return the minimum path sum at the bottom-right cell
    }
}
```
