← Infosys bank

Infosys · Question 15 · Arrays

Maximum Sum Circular Subarray

ArraysC++code⏱ O(n)💾 O(n)
Service-based

Problem

Find the maximum subarray sum in a circular array.

Approach

Find the max subarray (Kadane), find the min subarray, subtract from the total for the wrap-around case.

Time O(n)Space O(n)

How it works

  1. 1Plain Kadane gives the non-wrapping best.
  2. 2Total minus min-subarray gives the wrapping best.
  3. 3All-negative input falls back to plain Kadane.

Sample input / output

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

Constraints

1 <= n <= 3 * 10^4.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 2Branches 1Returns 4source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeatyesnoSTARTinclude <iostream>include <vector>include <algorithm>using namespace stdDEFINE kadane(constvector<int>& nums)DEFINE max_ending =nums[0], max_so_far =nums[0]for (size_t i = 1; i <nums.size(); i++)max_ending = max(nums[i],max_ending + nums[i])max_so_far =max(max_so_far, max_ending)RETURN max_so_farDEFINEmaxSubarrayCircular(constvector<int>& nums)DEFINE max_kadane =kadane(nums)DEFINE total = 0vector<int>inverted(nums.size())for (size_t i = 0; i <nums.size(); i++)total += nums[i]inverted[i] = -nums[i]DEFINE max_inverted =kadane(inverted)DEFINE max_circular = total+ max_invertedif (max_circular == 0)RETURN max_kadaneRETURN max(max_kadane,max_circular)DEFINE main()vector<int> nums = {1, -2,3, -2}cout <<maxSubarrayCircular(nums)<< endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/27

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits