/*
Problem: Sum of Travel Times with Toggling Lights
Company Tag: Infosys OA
Problem Statement:
We are given a binary array v of length n.
v[i] = 1 means light is initially ON.
v[i] = 0 means light is initially OFF.
There are positions from 0 to n.
To move from position x to x + 1:
light at position x + 1 must be ON.
Each move takes 1 second.
Each wait also takes 1 second.
After every second:
all lights toggle.
For every pair (i, j), where 0 <= i < j <= n:
calculate minimum travel time from i to j.
Return sum of all travel times modulo 1e9 + 7.
Constraints:
Exact constraints were not mentioned.
This solution is O(n), so it works for large n.
Brute Force:
For every pair, simulate movement and toggling.
Why Brute Force Fails:
There are O(n^2) pairs.
Simulation for each pair is too slow.
Optimized Idea:
Every pair (i, j) represents one substring of lights.
For first light:
ON -> cost 1
OFF -> cost 2
For next lights:
If current light is different from previous light -> cost 1
Otherwise -> cost 2
Explanation Block:
Instead of simulating every substring, I calculate contribution.
Contribution types:
1. First light of every substring.
2. Adjacent transition inside substrings.
For transition between i - 1 and i:
It appears in i * (n - i) substrings.
Dry Run:
v = [1, 0]
Pairs:
(0, 1): time = 1
(1, 2): time = 2
(0, 2): time = 2
Total = 5
Time Complexity:
O(n)
Space Complexity:
O(1)
*/
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1000000007LL;
long long sumOfTravelTimes(vector<int>& v) {
int n = v.size();
long long ans = 0;
// Contribution of first light of every substring.
for (int i = 0; i < n; i++) {
// If first light is ON, move directly.
// If OFF, wait once and then move.
long long cost = (v[i] == 1 ? 1 : 2);
// Number of substrings starting at i.
long long count = n - i;
ans = (ans + cost * count) % MOD;
}
// Contribution of adjacent transitions.
for (int i = 1; i < n; i++) {
// If current light differs from previous,
// movement takes 1 second.
// Otherwise, wait + move = 2 seconds.
long long cost = (v[i] != v[i - 1] ? 1 : 2);
// Transition between i - 1 and i appears in i * (n - i) substrings.
long long count = 1LL * i * (n - i);
ans = (ans + cost * (count % MOD)) % MOD;
}
return ans;
}
int main() {
vector<int> v = {1, 0};
cout << sumOfTravelTimes(v) << endl;
return 0;
}