From d925ef998de5aeb1ad829bc95014c0b0f3b5c4e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A2=D0=B8=D1=89=D0=B5=D0=BD=D0=BA=D0=BE=20=D0=9A=D0=BE?= =?UTF-8?q?=D0=BD=D1=81=D1=82=D0=B0=D0=BD=D1=82=D0=B8=D0=BD=20=D0=A2=D0=B8?= =?UTF-8?q?=D0=BC=D1=83=D1=80=D0=BE=D0=B2=D0=B8=D1=87=20=284063341=29?= Date: Wed, 29 Jun 2022 00:14:03 +0300 Subject: [PATCH] 303. Range Sum Query - Immutable --- DP/RangeSumQueryImmutable.swift | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 DP/RangeSumQueryImmutable.swift diff --git a/DP/RangeSumQueryImmutable.swift b/DP/RangeSumQueryImmutable.swift new file mode 100644 index 00000000..989c054e --- /dev/null +++ b/DP/RangeSumQueryImmutable.swift @@ -0,0 +1,27 @@ +/** + * Question Link: https://leetcode.com/problems/range-sum-query-immutable/ + * Primary idea: Calculate the sum of the elements of nums between indices left and right + * Time Complexity: O(n), Space Complexity: O(1) + * + */ + +class NumArray { + var sums: [Int] = [] + + init(_ nums: [Int]) { + var currentSum = 0 + + for num in nums { + currentSum += num + sums.append(currentSum) + } + print(sums) + } + + func sumRange(_ left: Int, _ right: Int) -> Int { + if left == 0 { + return sums[right] + } + return sums[right] - sums[left-1] + } +}