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.
Example 1:
Input: prices = [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7.
Example 2:
Input: prices = [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4.
Example 3:
Input: prices = [7,6,4,3,1] Output: 0 Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
Constraints:
1 <= prices.length <= 3 * 1040 <= prices[i] <= 104가격 배열 가격이 주어지며, 가격[i]는 해당 날짜에 지정된 주식의 가격입니다.
매일 주식을 매수 및/또는 매도할 수 있습니다. 한 번에 최대 한 종목의 주식만 보유할 수 있습니다. 그러나 매수한 후 같은 날 즉시 매도할 수 있습니다.
달성할 수 있는 최대 수익을 찾아서 반환하세요.
입력: prices = [7,1,5,3,6,4]
출력: 7
설명: 2일차에 매수(가격 = 1)하고 3일차에 매도(가격 = 5), 수익 = 5-1 = 4입니다.
그런 다음 4일째에 매수(가격 = 3)하고 5일째에 매도(가격 = 6)하면 수익 = 6-3 = 3이 됩니다.
총 수익은 4 + 3 = 7입니다.
최소 값이 고정되지 않고 계속 바뀌는 형식이니깐 Best Time to Buy and Sell Stock I 과는 다르게 접근해야한다.
배열을 순회하면서 전에 인덱스 - 1이 인덱스 값보다 크다면 수익이 나는 구조이니깐 서로 감산한 결과값을 인수에 담아서 그 인수를 반환한다.
int 합산;
for (1, 배열 길이, 1씩 증가) {
if (어제 날짜 < 현재 날짜) {
합산에 저장 = 현재 날짜 - 어제 날짜;
}
}
합산 반환;
class Solution {
public int maxProfit(int[] prices) {
int result = 0;
for (int i = 1; i < prices.length; i++) {
// 전날 가격보다 다음 날 가격이 크다면
if (prices[i -1] < prices[i]) {
// 수익 적립
result += prices[i] - prices[i - 1];
}
}
}
}
public int maxProfit(int[] prices) {
int result = 0;
for (int i = 1; i <prices.length; i++) {
result += Math.max(prices[i] - prices[i -1], 0);
}
}
Math 클래스를 활용한 다른 답안이다. 0보다 크다면 수익이 난다는 의미이니깐 0과 비교하여 최대값을 찾고 result에 적립하는 구조이다.
내가 작성했던 분기문들은 중복되는 키워드가 많았다. 아무래도 한줄에 작성되는 이런 코드가 보기에 깔끔하기도 하고 직관적이라서 좋다. 리팩토링을 통해서 이렇게 간단하게 표현할 수 있도록 개선나가야겠다.