p122

LeetCode 122 Best Time to Buy and Sell Stock II 题解

1.题目:

Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit.
You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times).
However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

题意:

输入一个数组,是每天股票的价格,进行买入卖出操作,返回你可以获得的最大利润。

2.解题思路:

贪心

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 
package leetcode;

import java.util.Scanner;

public class p122 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = in.nextLine();

int[] nn1 = new int[(a.length() + 1) / 2];
String[] n1 = a.split(" ");

for (int i = 0; i < (a.length() + 1) / 2; i++) {
nn1[i] = Integer.parseInt(n1[i]);
// System.out.println(nn1[i]);
}

// 完成数据的输入并进行处理
int ans;
ans = maxProfit(nn1);

System.out.print(ans + " ");

}

public static int maxProfit(int[] prices) {

int max = 0;
if (prices == null || prices.length < 2) {
return 0;
}
for (int i = 1; i < prices.length; i++) {
if (prices[i] - prices[i - 1] > 0) {
max = max + prices[i] - prices[i - 1];
}
}
return max;
}

}



4.一些总结: