Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Length of longest subsequence of Fibonacci Numbers in an Array
Next article icon

Length of the longest ZigZag Subsequence of the given Array

Last Updated : 24 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of integers, if the differences between consecutive numbers alternate between positive and negative. More formally, if arr[i] - arr[i-1] has a different sign for all i from 1 to n-1, the subsequence is considered a zig-zag subsequence. Find out the length of the longest Zig-Zag subsequence of the given array.

Examples:

Input: arr[] = {1, 7, 4, 9, 2, 5}
Output: 6
Explanation: The entire sequence is a zig-zag sequence.

Input: arr[] = {1, 17, 5, 10, 13, 15, 10, 5, 16, 8}
Output: 7
Explanation: The zig-zag subsequence is [1, 17, 10, 13, 10, 16, 8].

Approach: To solve the problem follow the below idea:

We can solve this problem using Dynamic Programming.

Follow the steps to solve the problem:

  • Create two arrays, up and down, both of the same length as the input array. The up[i] array will store the length of the longest zig-zag subsequence ending at index i and having the last difference as positive. Similarly, the down[i] array will store the length of the longest zig-zag subsequence ending at index i and having the last difference as negative.
  • Initialize both up and down arrays with values of 1 since any single element is a valid zig-zag subsequence of length 1.
  • For each index i from 1 to n-1, compare the current element arr[i] with the previous element arr[i-1]. If arr[i] is greater, update up[i] using the maximum of up[i] and down[i-1] + 1, since the last difference is negative and now you have a positive difference.
  • If arr[i] is smaller, update down[i] using the maximum of down[i] and up[i-1] + 1, since the last difference is positive and now you have a negative difference.
  • The maximum value between up and down arrays at index n-1 will be the answer.

Below is the implementation of the above idea:

C++14
// C++ program to find longest Zig-Zag // subsequence in an array #include <algorithm> #include <iostream> #include <vector> using namespace std;  int longestZigZag(vector<int>& arr) {     int n = arr.size();     vector<int> up(n, 1);     vector<int> down(n, 1);      for (int i = 1; i < n; i++) {         for (int j = 0; j < i; j++) {             if (arr[i] > arr[j]) {                  // up[i] array will store the                 // length of the longest zig-zag                 // subsequence ending at index i                 up[i] = max(up[i], down[j] + 1);             }             else if (arr[i] < arr[j]) {                  // down[i] array will store the                 // length of the longest zig-zag                 // subsequence ending at index i                 down[i] = max(down[i], up[j] + 1);             }         }     }      return max(up[n - 1], down[n - 1]); }  // Drivers code int main() {     vector<int> arr         = { 1, 17, 5, 10, 13, 15, 10, 5, 16, 8 };      // Function Call     cout << longestZigZag(arr) << endl;      return 0; } 
Java
// Java program to find longest // Zig-Zag subsequence in an array public class GFG {     // Function to return longest     // Zig-Zag subsequence length     public static int longestZigZag(int[] arr) {         int n = arr.length;         int[] up = new int[n];         int[] down = new int[n];                  //initialize both up and down arrays with values of 1         for (int i = 0; i < n; i++) {             up[i] = 1;             down[i] = 1;         }          for (int i = 1; i < n; i++) {             for (int j = 0; j < i; j++) {                 if (arr[i] > arr[j]) {                     // up[i] array will store the length of the longest zig-zag subsequence ending at index i                     up[i] = Math.max(up[i], down[j] + 1);                 } else if (arr[i] < arr[j]) {                     // down[i] array will store the length of the longest zig-zag subsequence ending at index i                     down[i] = Math.max(down[i], up[j] + 1);                 }             }         }          return Math.max(up[n - 1], down[n - 1]);     }      public static void main(String[] args) {         int[] arr = {1, 7, 4, 9, 2, 5};         System.out.println(longestZigZag(arr));       } }  // This code is contributed by spbabaraheem 
Python3
# Python3 program to find longest # Zig-Zag subsequence in an array def longestZigZag(arr):     n = len(arr)     up = [1] * n     down = [1] * n      for i in range(1, n):         for j in range(i):             if arr[i] > arr[j]:                 # up[i] array will store the length of the longest zig-zag subsequence ending at index i                 up[i] = max(up[i], down[j] + 1)             elif arr[i] < arr[j]:                 # down[i] array will store the length of the longest zig-zag subsequence ending at index i                 down[i] = max(down[i], up[j] + 1)      return max(up[-1], down[-1])  # Example usage arr = [1, 7, 4, 9, 2, 5] print(longestZigZag(arr))    # This code is contributed by spbabaraheem 
C#
// C# program to find longest // Zig-Zag subsequence in an array using System; using System.Collections.Generic;  public class Program {     // Function to return longest     // Zig-Zag subsequence length     public static int LongestZigZag(int[] arr)     {         int n = arr.Length;         int[] up = new int[n];         int[] down = new int[n];                  //initialize both up and down arrays with values of 1         for (int i = 0; i < n; i++) {           up[i] = 1;           down[i] = 1;         }                for (int i = 1; i < n; i++)         {             for (int j = 0; j < i; j++)             {                 // up[i] array will store the length of the longest zig-zag subsequence ending at index i                 if (arr[i] > arr[j])                 {                     up[i] = Math.Max(up[i], down[j] + 1);                 }                 else if (arr[i] < arr[j])                 {                     // down[i] array will store the length of the longest zig-zag subsequence ending at index i                     down[i] = Math.Max(down[i], up[j] + 1);                 }             }         }          return Math.Max(up[n - 1], down[n - 1]);     }      public static void Main()     {         int[] arr = { 1, 17, 5, 10, 13, 15, 10, 5, 16, 8 };          // Function Call         Console.WriteLine(LongestZigZag(arr));     } } // This code is contributed by Rohit Singh 
JavaScript
function longestZigZag(arr) {     let n = arr.length;     let up = Array(n).fill(1);     let down = Array(n).fill(1);      for (let i = 1; i < n; i++) {         for (let j = 0; j < i; j++) {             if (arr[i] > arr[j]) {                 up[i] = Math.max(up[i], down[j] + 1);             } else if (arr[i] < arr[j]) {                 down[i] = Math.max(down[i], up[j] + 1);             }         }     }      return Math.max(up[n - 1], down[n - 1]); }  // Driver code let arr = [1, 17, 5, 10, 13, 15, 10, 5, 16, 8];  // Function call console.log(longestZigZag(arr)); 

Output
7

Time Complexity: O(n2)
Auxiliary Space: O(n)


Next Article
Length of longest subsequence of Fibonacci Numbers in an Array

S

spbabaraheem123
Improve
Article Tags :
  • Dynamic Programming
  • DSA
Practice Tags :
  • Dynamic Programming

Similar Reads

  • Length of the longest ZigZag subarray of the given array
    Given an array arr[] containing n numbers, the task is to find the length of the longest ZigZag subarray such that every element in the subarray should be in form a < b > c < d > e < f Examples: Input: arr[] = {12, 13, 1, 5, 4, 7, 8, 10, 10, 11} Output: 6 Explanation: The subarray is
    7 min read
  • Find length of the longest non-intersecting anagram Subsequence
    Given a string S of length N, find the length of the two longest non-intersecting subsequences in S that are anagrams of each other. Input: S = "aaababcd"Output: 3Explanation: Index of characters in the 2 subsequences are: {0, 1, 3} = {a, a, b} {2, 4, 5} = {a, a, b} The above two subsequences of S a
    6 min read
  • Length of longest subsequence whose XOR value is odd
    Given an array arr[] of N positive integers, the task is to find the length of the longest subsequence such that Bitwise XOR of all integers in the subsequence is odd. Examples: Input: N = 7, arr[] = {2, 3, 4, 1, 5, 6, 7}Output: 6Explanation: The subsequence of maximum length is {2, 3, 4, 5, 6, 7} w
    7 min read
  • Longest subsequence with a given AND value | O(N)
    Given an array arr[], the task is to find the longest subsequence with a given AND value M. If there is no such sub-sequence then print 0.Examples: Input: arr[] = {3, 7, 2, 3}, M = 3 Output: 3 {3, 7, 3} is the required subsequence. 3 & 7 & 3 = 3Input: arr[] = {2, 2}, M = 3 Output: 0 Naive ap
    5 min read
  • Length of longest subsequence of Fibonacci Numbers in an Array
    Given an array arr containing non-negative integers, the task is to print the length of the longest subsequence of Fibonacci numbers in this array.Examples: Input: arr[] = { 3, 4, 11, 2, 9, 21 } Output: 3 Here, the subsequence is {3, 2, 21} and hence the answer is 3.Input: arr[] = { 6, 4, 10, 13, 9,
    5 min read
  • Length of Longest Increasing Subsequences (LIS) using Segment Tree
    Given an array arr[] of size N, the task is to count the number of longest increasing subsequences present in the given array. Example: Input: arr[] = {2, 2, 2, 2, 2}Output: 5Explanation: The length of the longest increasing subsequence is 1, i.e. {2}. Therefore, count of longest increasing subseque
    15+ min read
  • Length of longest increasing prime subsequence from a given array
    Given an array arr[] consisting of N positive integers, the task is to find the length of the longest increasing subsequence consisting of Prime Numbers in the given array. Examples: Input: arr[] = {1, 2, 5, 3, 2, 5, 1, 7}Output: 4Explanation:The Longest Increasing Prime Subsequence is {2, 3, 5, 7}.
    9 min read
  • Maximize length of longest increasing prime subsequence from the given array
    Given an array, arr[] of size N, the task is to find the length of the longest increasing prime subsequence possible by performing the following operations. If arr[i] is already a prime number, no need to update arr[i].Update non-prime arr[i] to the closest prime number less than arr[i].Update non-p
    13 min read
  • Length of the longest subsequence consisting of distinct elements
    Given an array arr[] of size N, the task is to find the length of the longest subsequence consisting of distinct elements only. Examples: Input: arr[] = {1, 1, 2, 2, 2, 3, 3} Output: 3 Explanation: The longest subsequence with distinct elements is {1, 2, 3} Input: arr[] = { 1, 2, 3, 3, 4, 5, 5, 5 }
    4 min read
  • Longest subsequence of even numbers in an Array
    Given an array arr[] containing N integers, the task is to print the length of the longest subsequence of even numbers in the array. Examples: Input: arr[] = {3, 4, 11, 2, 9, 21} Output: 2 Explanation: The longest subsequence containing even numbers is {4, 2}. Hence, the answer is 2. Input: arr[] =
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences