gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
Optimize the time complexity for this code: long long MinCost(int n, int weightsArr[]){…
- User
Optimize the time complexity for this code: long long MinCost(int n, int weightsArr[]){
long long minCost = INT_MAX; long long optimalIndex = -1; int totalWeightSum = 0; int weightedIndexSum = 0; for (int i = 0; i < n; i++) { totalWeightSum += weightsArr[i]; weightedIndexSum += i * weightsArr[i]; } for (int k = 0; k < n; k++) { long long totalCost = 0; for (int i = 0; i < n; i++) { totalCost += abs(k - i) * weightsArr[i]; } if (totalCost < minCost) { minCost = totalCost; optimalIndex = k; } } return minCost; } - Assistant
We can optimize the time complexity by removing the nested loop. Instead of looping through all elements for every value of
k, we can directly compute the next total cost from the previous one, by just adding the difference coming from the shift. Here's the updated code:long long MinCost(int n, int weightsArr[]){
long long minCost = INT_MAX; long long optimalIndex = -1; int totalWeightSum = 0; int weightedIndexSum = 0; for (int i = 0; i < n; i++) { totalWeightSum += weightsArr[i]; weightedIndexSum += i * weightsArr[i]; } long long totalCost = weightedIndexSum; for (int k = 0; k < n; k++) { if (totalCost < minCost) { minCost = totalCost; optimalIndex = k; } // Update totalCost for the next element totalCost = totalCost - totalWeightSum + n * weightsArr[k]; } return minCost;}
The time complexity of this optimized code is now O(n) instead of the O(n^2) from the original version.