DEV Community

Cover image for [C++ CODE] Almost Increasing Sum
✨ thetealpickle πŸ“±
✨ thetealpickle πŸ“±

Posted on

1

[C++ CODE] Almost Increasing Sum

THE TEAL PICKLE CODING CHALLENGE!! Determine whether the sequence is almost increasing. I solved this problem with bae (C++). TRY IT πŸ‘€

Check out my solution and share yours!! ~ πŸ’» πŸ’»

Top comments (1)

Collapse
 
itsjp profile image
Jaydeep Pipaliya β€’
#include <vector>
#include <iostream>

bool canBeIncreasing(std::vector<int>& sequence) {
    int count = 0;
    for (int i = 1; i < sequence.size(); ++i) {
        if (sequence[i] <= sequence[i - 1]) {
            count++;
            if (count > 1) {
                return false;
            }
            if (i > 1 && i < sequence.size() - 1 && sequence[i - 2] >= sequence[i] && sequence[i - 1] >= sequence[i + 1]) {
                return false;
            }
        }
    }
    return true;
}

int main() {
    std::vector<int> sequence1 = {1, 3, 2, 1};
    std::vector<int> sequence2 = {1, 3, 2};
    std::vector<int> sequence3 = {1, 2, 1, 2};
    std::vector<int> sequence4 = {10, 1, 2, 3};

    std::cout << canBeIncreasing(sequence1) << std::endl; // Output: 0 (false)
    std::cout << canBeIncreasing(sequence2) << std::endl; // Output: 1 (true)
    std::cout << canBeIncreasing(sequence3) << std::endl; // Output: 0 (false)
    std::cout << canBeIncreasing(sequence4) << std::endl; // Output: 1 (true)

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Initial Solution: O(n2) time complexity due to nested loops and repetitive checks.
Optimized Solution: O(n) time complexity due to a single pass through the sequence and constant time checks.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay