> For the complete documentation index, see [llms.txt](https://hannahpun.gitbook.io/leetcode-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hannahpun.gitbook.io/leetcode-note/array/724-find-pivot-index.md).

# # 724 Find Pivot Index

先算 total, Lsum 要等於 Rsum

[LeetCode](https://leetcode.com/problems/find-pivot-index/)

````javascript
/*Input: nums = [1,7,3,6,5,6]
Output: 3

Input: nums = [1,2,3]
Output: -1

Input: nums = [2,1,-1]
Output: 0 */

/**
 * @param {number[]} nums
 * @return {number}
 */
var pivotIndex = function(nums) {
    let total = nums.reduce((acc, cur) => cur + acc, 0)
    let pivot = 0;
    let Lsum = 0;
    let Rsum = total - nums[pivot];

    while(pivot < nums.length){
        if(Lsum === Rsum) {
            return pivot
        }
        Lsum += nums[pivot]
        pivot ++;
        Rsum -= nums[pivot]
    }
    
    return -1

    
};
```
````

### Edge Case

* 相加可能會是負值

### 怎麼解

* 一開始我是用 two pointer 但無法滿足 `[0, 1, -1 ]` 或是 `[-1,-1,-1,-1,-1,0]` 這種狀況
* 只要左右對 Lsum 跟 Rsum，一開始設定 Pivot 是 0，逐步檢查到 `Lsum === Rsum` 為止

<pre><code>     [-1, -1, -1, -1, -1, 0]
<strong>     ----
</strong>     Pivot
Lsum = 0   Rsum = -5(total) - -1 = -4

    [-1, -1, -1, -1, -1, 0]
        ----
        Pivot
Lsum = -1   Rsum = -3

    [-1, -1, -1, -1, -1, 0]
             ----
            Pivot (answer)
   Lsum = -2     Rsum = -2
</code></pre>
