[LeetCode] 122. Best Time to Buy and Sell Stock II - Java

wanuki·2023년 8월 23일
0

문제

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

구현 전 예상 풀이

이웃하는 값의 차가 양의 정수면 수익이 생긴다.
수익의 누적합을 구하겠다

구현 코드

class Solution {
    public int maxProfit(int[] prices) {
        int accumulation = 0;

        for (int i = 1; i < prices.length; i++) {
            int profit = prices[i] - prices[i - 1];
            if (profit > 0)
                accumulation += profit;
        }

        return accumulation;
    }
}

122. Best Time to Buy and Sell Stock II

profile
하늘은 스스로 돕는 자를 돕는다

0개의 댓글