[Hacker Rank] Sherlock and Cost

Sherlock and Cost

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
long long cost(vector<int> A) {
long long small = 0, big = 0, n = A.size();
for(int i = 1; i < n; i++) {
auto nbig = max(big + abs(A[i - 1] - A[i]),small + abs(A[i] - 1));
auto nsmall = big + abs(A[i - 1] - 1);
big = nbig;
small = nsmall;
}
return max(small, big);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/13/PS/HackerRank/sherlock-and-cost/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.